<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class Order extends AuthAndBind{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 后台审核商家入驻(关联变更下单人账号类型及权限)
	 */
	public function adminVerifyOrderGoodsType3(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> lock(true) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['status'] != 2 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				if( $oldData['goods_type'] != 3 ) returnResults2('-1', '操作失败,订单商品有误,请联系管理员');
				
				
				Db::startTrans();
				$save['status'] = $in['status'];
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '审核失败,请联系管理员');
				}
				
				if( $save['status'] == 1 ){
					$createOrderUserWhere[] = ['id', 'eq', $oldData['create_user_id']];
					$createOrderUser = Db::table("gd_user") -> where($createOrderUserWhere) -> find();
					if( $createOrderUser['type'] != 3 ){
						$saveCreateOrderUser['type'] = 3;
						$re = Db::table("gd_user") -> where($createOrderUserWhere) -> update($saveCreateOrderUser);
						if( !$re ){
							Db::rollback();
							returnResults2('-1', '变更下单用户账号失败,请联系管理员');
						}
						
						$oldCreateOrderUserGroupAccessWhere['uid'] = $createOrderUser['id'];
						$oldCreateOrderUserGroupAccess = Db::table("gd_auth_group_access") -> where($oldCreateOrderUserGroupAccessWhere) -> find();
						if( !empty($oldCreateOrderUserGroupAccess) ){
							$res = Db::table("gd_auth_group_access") -> where($oldCreateOrderUserGroupAccessWhere) -> delete();
							if( !$res ){
								Db::rollback();
								returnResults2('-1', '删除原权限失败,请联系管理员');
							}
							$newAuthGroupAccess['uid'] = $createOrderUser['id'];
							$newAuthGroupAccess['group_id'] = 2;
							$res = Db::table("gd_auth_group_access") -> insertAll($newAuthGroupAccess);
							if( !$res ){
								Db::rollback();
								returnResults2('-1', '新增权限失败,请联系管理员');
							}
						}
					}
				}
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台审核商家入驻(关联变更下单人账号类型及权限)',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台审核代理商入驻
	 */
	public function adminVerifyOrderGoodsType4(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> lock(true) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['status'] != 2 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				if( $oldData['goods_type'] != 4 ) returnResults2('-1', '操作失败,订单商品有误,请联系管理员');
				
				$save['status'] = $in['status'];
				
				Db::startTrans();
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '审核失败,请联系管理员');
				}
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台审核代理商入驻',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户获取子订单商量列表
	 */
	public function userGetOrderSubGoodsList(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where = [];
				$where[] = ['a.create_user_id', 'eq', $in['user_id']];
				$where[] = ['a.status', 'in', [1, 12]];
				$field = ['d.*', 'c.nums', 'b.price1', 'b.price2', 'a.create_user_id'=>'main_order_shop_user_id', 'b.id'=>'order_subgoods_id', 'a.id'=>'parent_order_id', 'd.id'=>'goods_id'];
				
				$data = Db::table("gd_order") -> alias('a')
											-> join('gd_order_subgoods b', 'a.id = b.order_id') 
											-> join('gd_goods_subgoods c', 'c.id = b.goods_subgoods_id') 
											-> join('gd_goods d', 'd.id = c.sub_goods_id') 
											-> where($where) -> field($field) -> order("a.id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_order") -> alias('a')
											-> join('gd_order_subgoods b', 'a.id = b.order_id') 
											-> join('gd_goods_subgoods c', 'c.id = b.goods_subgoods_id') 
											-> join('gd_goods d', 'd.id = c.sub_goods_id') 
											-> count();
				
				if( !empty($data) ){
					
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户获取子订单商量列表',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台核销订单
	 */
	public function writeOffOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'write_off_status', 'nums'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['status'] != 2 ) returnResults2('-1', '操作失败,该订单状态有误');
				if( $oldData['goods_type'] != 2 ) returnResults2('-1', '操作失败,该订单无需核销');
				if( $oldData['write_off_status'] != 0 ) returnResults2('-1', '操作失败,该订单无需核销');
				
				$goodsNums = $oldData['goods_nums'] * $oldData['num'];
				
				$orderWriteoffNums = Db::table("gd_order_writeoff") -> where(['order_id'=>$in['id']]) -> sum("nums");
				if( $orderWriteoffNums >= $goodsNums || $in['nums'] + $orderWriteoffNums > $goodsNums )  returnResults2('-1', '操作失败,该订单最大剩余核销数量【'.($goodsNums-$orderWriteoffNums).'】');
				
				$newData['order_id'] = $in['id'];
				$newData['nums'] = $in['nums'];
				$newData['check_date'] = date("Y-m-d H:i:s", time());
				$newData['check_user_id'] = $userInfo['info']['id'];
				$newData['check_user_name'] = $userInfo['info']['nickname'];
				$newData['check_user_type'] = $userInfo['info']['type'];
				
				Db::startTrans();
				$res = Db::table("gd_order_writeoff") -> insertGetId($newData);
				if( !$res ){
					Db::rollback();
					returnResults2('-1', '新增记录失败,请联系管理员');
				}
				
//				订单所有数量核销完成
				if( $in['nums'] + $orderWriteoffNums == $goodsNums ){
					$save['write_off_status'] = $in['write_off_status'];
					$save['write_off_user_id'] = $userInfo['info']['id'];
					$save['write_off_user_name'] = $userInfo['info']['nickname'];
					$save['status'] = 12;
					$save['write_off_date'] = date("Y-m-d H:i:s", time());
					$save = filterArr($save, array_keys($save), $oldData);
					if( !empty($save) ){
						$re = Db::table("gd_order") -> where($where) -> update($save);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '核销失败,请联系管理员');
						}
					}
					
//					处理订单各级返佣
//					$oldReward = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> select();
//					if( !empty($oldReward) ){
////						变更奖励为生效
//						$res = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> update(['withdrawal_status'=>'0']);
//						if( !$res ){
//							Db::rollback();
//							returnResults2('-1', '变更奖励状态失败,请联系管理员');
//						}
//						
////						给用户账号加余额
//						foreach ($oldReward as $k => $v) {
//							$re = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('rebate', $v['rewards']);
//							$re = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('total_income', $v['rewards']);
//							if( !$re ) {
//								Db::rollback();
//								returnResults2('-1', '变更用户信息失败,请联系管理员');
//							}
//						}
//					}
					
//					处理下单人的积分
					$newUserIntegral['num'] = $oldData['actual_price'];
					$newUserIntegral['type'] = 1;
					$newUserIntegral['integral_user_id'] = $in['user_id'];
					$newUserIntegral['create_user_id'] = $in['user_id'];
					$newUserIntegral['create_user_name'] = $userInfo['info']['nickname'];
					$newUserIntegral['create_user_type'] = $userInfo['info']['type'];
					$newUserIntegral['create_date'] = date("Y-m-d H:i:s", time());
					$re = Db::table("gd_user_integral") -> insertGetId($newUserIntegral);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '生成积分明细失败,请联系管理员');
					}
					
					$re = Db::table("gd_user") -> where(['id'=>$userInfo['info']['id']]) -> setInc('integral', $newUserIntegral['num']);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '变更用户积分失败,请联系管理员');
					}
				}
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台核销订单',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台售后退款(订单)
	 */
	public function adminRefund(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'order_id', 'refund_type', 'refund_file'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['order_id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['refund_applyfor_status'] != 2 || $oldData['status'] != 4 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['status'] = 5;
				
				Db::startTrans();
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '发货失败,请联系管理员');
				}
				
//				同意退款
				if( $oldData['refund_applyfor_status'] == 2 ){
					
					$refund_file = '';
					if( isset($in['refund_file']) ){
						$refund_file = is_array($in['refund_file']) ? json_encode($in['refund_file']) : $in['refund_file'];
					}
					
//					订单由微信小程序支付
					if( $oldData['pay_type'] == 1 ){
//						处理微信支付记录
						$save3['refund_status'] = 1;
						$save3['refund_price'] = $oldData['refund_applyfor_price'];
						$save3['refund_date'] = date("Y-m-d H:i:s", time());
						$save3['refund_type'] = isset($in['refund_type']) ? $in['refund_type'] : '';
						$save3['refund_file'] = $refund_file;
						$save3['refund_create_date'] = $oldData['refund_applyfor_date'];
						$save3['refund_desc'] = $oldData['refund_applyfor_reason'];
						
						$paymentRecordsWhere[] = ['order_id', 'eq', $oldData['id']];
						$paymentRecordsWhere[] = ['pay_status', 'eq', 1];
						$re = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update($save3);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '变更支付记录数据失败,请联系管理员');
						}
					}
					
//					原路退款 并且 订单由余额支付，退到余额
					if( $in['refund_type'] == 1 && $oldData['pay_type'] == 9 ){
						$userWhere['id'] = $oldData['create_user_id'];
						$orderUser = Db::table("gd_user") -> where($userWhere) -> find();
						
						$saveUserRe = Db::table("gd_user") -> where($userWhere) -> setInc('recharge_balance', $oldData['actual_price']);
						if( !$saveUserRe ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'增加用户余额失败,请联系管理员']);
						}
						
						$newRechargeRecord['user_id'] = $oldData['create_user_id'];
						$newRechargeRecord['first_money'] = $orderUser['recharge_balance'];
						$newRechargeRecord['after_money'] = $orderUser['recharge_balance'] + $oldData['actual_price'];
						$newRechargeRecord['money'] = $oldData['actual_price'];
						$newRechargeRecord['type'] = 3;
						$newRechargeRecord['state'] = 1;
						$newRechargeRecord['order_id'] = $oldData['id'];
						$newRechargeRecord['create_user_id'] = $oldData['create_user_id'];
						$newRechargeRecord['create_user_name'] = $oldData['create_user_name'];
						$newRechargeRecord['create_user_type'] = $oldData['create_user_type'];
						$newRechargeRecord['create_date'] = date("Y-m-d H:i:s", time());
						$re = Db::table("gd_recharge_record") -> insertGetId($newRechargeRecord);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>'-1', 'msg'=>'生成余额变动记录失败,请联系管理员']);
						}
					}
				}
				
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台售后审核',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户填写退货运单信息（售后）
	 */
	public function userEditRefundApplyforWaybill(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'refund_applyfor_waybill_code'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] != 0 || $oldData['refund_applyfor_status'] != 2 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['refund_applyfor_waybill_code'] = $in['refund_applyfor_waybill_code'];
				$save['refund_applyfor_waybill_name'] = isset($in['refund_applyfor_waybill_name']) ? $in['refund_applyfor_waybill_name'] : '';
				$save['refund_applyfor_waybill_status'] = 1;
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '修改失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户填写退货运单信息（售后）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台售后审核
	 */
	public function adminVerifyAftersales(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['refund_applyfor_status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['refund_applyfor_status'] = $in['refund_applyfor_status'];
				$save['refund_applyfor_status3_reason'] = isset($in['refund_applyfor_status3_reason']) ? $in['refund_applyfor_status3_reason'] : $oldData['refund_applyfor_status3_reason'];
				$save['refund_applyfor_status_date'] = date("Y-m-d H:i:s", time());
				if( $in['refund_applyfor_status'] == 2 && $oldData['refund_applyfor_price'] > 0 ) $save['status'] = 4;
				if( $in['refund_applyfor_status'] == 2 ) $save['refund_applyfor_waybill_status'] = 2;
				
				Db::startTrans();
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '发货失败,请联系管理员');
				}
				
//				同意退款
				if( $save['refund_applyfor_status'] == 2 ){
//					处理鉴定
					if( $oldData['is_identify'] == 1 ){
						$save2['refund_type'] = $oldData['refund_type'];
						$save2['refund_applyfor_price'] = $oldData['refund_applyfor_price'];
						$save2['refund_applyfor_file'] = $oldData['refund_applyfor_file'];
						$save2['refund_applyfor_reason'] = $oldData['refund_applyfor_reason'];
						$save2['refund_applyfor_date'] = $oldData['refund_applyfor_date'];
						$save2['refund_applyfor_status'] = $save['refund_applyfor_status'];
						$save2['refund_applyfor_status_date'] = $save['refund_applyfor_status_date'];
						
						$identifyWhere[] = ['order_id', 'eq', $oldData['id']];
						$re = Db::table("gd_identify") -> where($identifyWhere) -> update($save2);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '变更鉴定数据失败,请联系管理员');
						}
					}
					
//					处理支付记录
//					$save3['refund_status'] = 1;
//					$save3['refund_price'] = $oldData['refund_applyfor_price'];
//					$save3['refund_date'] = date("Y-m-d H:i:s", time());
//					$save3['refund_type'] = isset($in['refund_type']) ? $in['refund_type'] : '';
//					$save3['refund_file'] = isset($in['refund_file']) ? $in['refund_file'] : '';
//					$save3['refund_create_date'] = $oldData['refund_applyfor_date'];
//					$save3['refund_desc'] = $oldData['refund_applyfor_reason'];
//					
//					$paymentRecordsWhere[] = ['order_id', 'eq', $oldData['id']];
//					$paymentRecordsWhere[] = ['pay_status', 'eq', 1];
//					$re = Db::table("gd_payment_records") -> where($paymentRecordsWhere) -> update($save3);
//					if( !$re ) {
//						Db::rollback();
//						returnResults2('-1', '变更鉴定支付记录数据失败,请联系管理员');
//					}
				}
				
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台售后审核',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户申请退款（售后）
	 */
	public function userApplyforRefund(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'refund_type', 'refund_applyfor_price', 'refund_applyfor_reason'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] != 0 || in_array($oldData['status'], [0, 6, 7, 10]) ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['refund_type'] = $in['refund_type'];
				$save['refund_applyfor_file'] = isset($in['refund_applyfor_file']) ? $in['refund_applyfor_file'] : '';
				$save['refund_applyfor_price'] = $in['refund_applyfor_price'];
				$save['refund_applyfor_reason'] = $in['refund_applyfor_reason'];
				$save['refund_applyfor_date'] = '0000-00-00 00:00:00';
				$save['refund_applyfor_status'] = 1;
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '修改失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户申请退款',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 获取分销订单列表
	 */
	public function getDistributionOrderList(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				$where[] = ['a.is_delete', 'eq', 0];
				if( isset($in['referrer_id']) && !empty($in['referrer_id']) ) $where[] = ['b.referrer_id', 'eq', $in['referrer_id']];
				if( isset($in['create_date']) ) $where[] = ['a.create_date', 'between', $in['create_date']];
				if( isset($in['status']) ) $where[] = ['a.status', 'in', $in['status']];
				if( isset($in['code']) ) $where[] = ['a.code', 'like', '%'.$in['code'].'%'];
				
				$field = ['a.*', 'b.referrer_id'];
				$data = Db::table("gd_order")   -> alias('a')
												-> join('gd_user b', 'a.create_user_id = b.id', 'left') 
												-> field($field)
												-> where($where) 
												-> order("a.id desc") 
												-> limit($start, $num) -> select();
				$count = Db::table("gd_order")   -> alias('a')
												-> join('gd_user b', 'a.create_user_id = b.id', 'left') 
												-> field($field)
												-> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$referrerUser = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> find();
						$data[$k]['referrerName'] = !empty($referrerUser) ? $referrerUser['nickname2'] : '';
						$data[$k]['referrerPhone'] = !empty($referrerUser) ? $referrerUser['phone'] : '';
						
						$createUser = Db::table("gd_user") -> where(['id'=>$v['create_user_id']]) -> find();
						$data[$k]['create_user_phone'] = !empty($createUser) ? $createUser['phone'] : '';
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取分销订单列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台发货
	 */
	public function adminSendGoods(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> lock(true) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['status'] != 2 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['status'] = 11;
				$save['waybill_code'] = isset($in['waybill_code']) ? $in['waybill_code'] : $oldData['waybill_code'];
				$save['waybill_name'] = isset($in['waybill_name']) ? $in['waybill_name'] : $oldData['waybill_name'];
				$save['send_goods_date'] = date("Y-m-d H:i:s", time());
				
				Db::startTrans();
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '发货失败,请联系管理员');
				}
				
				if( $oldData['source'] == 21 && in_array($oldData['delivery_type_id'], [2,3]) ){
//					变更订单状态
					$save['status'] = 1;
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '发货失败,请联系管理员');
					}
//					读取商品
					$oldGoods = Db::table("gd_goods") -> where(['id'=>$oldData['goods_id']]) -> find();
					if( !empty($oldGoods) ){
//						读取该商家的子商品
						$createOrderUserGoods = Db::table("gd_goods") -> where(['parent_id'=>$oldData['goods_id'], 'create_user_id'=>$oldData['create_user_id'], 'is_delete'=>0]) -> find();
						if( empty($createOrderUserGoods) ){
//							生成子商品
							$subGoods = $oldGoods;
							unset($subGoods['id']);
							$shop = Db::table("gd_shop") -> where(['create_user_id'=>$oldData['create_user_id']]) -> find();
							$subGoods['shop_id'] = empty($shop) ? 0 : $shop['id'];
							$subGoods['parent_id'] = $oldGoods['id'];
							$subGoods['create_user_id'] = $oldData['create_user_id'];
							$subGoods['create_user_name'] = $oldData['create_user_name'];
							$subGoods['create_user_type'] = $oldData['create_user_type'];
							$subGoods['create_date'] = date("Y-m-d H:i:s", time());
							$newGoodsId = Db::table("gd_goods") -> insertGetId($subGoods);
							if( !$newGoodsId ) {
								Db::rollback();
								returnResults2('-1', '生成新商品失败,请联系管理员');
							}
							
//							商品规格
							$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$oldData['goods_id'], 'is_delete'=>0]) -> select();
							if( !empty($oldGoodsSpec) ){
								$newGoodsSpec = [];
								foreach ($oldGoodsSpec as $k => $v) {
									$v['goods_id'] = $newGoodsId;
									$v['num'] = $oldData['goods_spec_id'] == $v['id'] ? $oldData['num'] : 0;
									$v['num2'] = $oldData['goods_spec_id'] == $v['id'] && in_array($oldData['delivery_type_id'], [3]) ? $oldData['num'] : 0;	//云仓
									$v['num3'] = $oldData['goods_spec_id'] == $v['id'] && in_array($oldData['delivery_type_id'], [2]) ? $oldData['num'] : 0;	//实仓	
									$v['create_user_id'] = $oldData['create_user_id'];
									$v['parent_id'] = $v['id'];
									$v['create_user_name'] = $oldData['create_user_name'];
									$v['create_user_type'] = $oldData['create_user_type'];
									$v['create_date'] = date("Y-m-d H:i:s", time());
									unset($v['id']);
									$newGoodsSpec[$k] = $v;
								}
								$newGoodsSpecRes = Db::table("gd_goods_spec") -> insertAll($newGoodsSpec);
								if( !$newGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '生成新商品规格失败,请联系管理员');
								}
							}
							
//							商品配送方式
							$oldGoodsDeliveryMethod = Db::table("gd_goods_delivery_method") -> where(['goods_id'=>$oldData['goods_id'], 'is_delete'=>0]) -> select();
							if( !empty($oldGoodsDeliveryMethod) ){
								$newGoodsDeliveryMethod = [];
								foreach ($oldGoodsDeliveryMethod as $k => $v) {
									unset($v['id']);
									$v['goods_id'] = $newGoodsId;
									$newGoodsDeliveryMethod[$k] = $v;
								}
								$newGoodsDeliveryMethodRes = Db::table("gd_goods_delivery_method") -> insertAll($newGoodsDeliveryMethod);
								if( !$newGoodsDeliveryMethodRes ) {
									Db::rollback();
									returnResults2('-1', '生成新商品配送方式失败,请联系管理员');
								}
							}
						}else{
//							读取下单用户该商品的规格
							$createOrderUserGoodsSpecWhere['goods_id'] = $createOrderUserGoods['id'];			//商品id
							$createOrderUserGoodsSpecWhere['parent_id'] = $oldData['goods_spec_id'];			//父级规格id
							$createOrderUserGoodsSpecWhere['create_user_id'] = $oldData['create_user_id'];		//创建人id
							$oldCreateOrderUserGoodsSpec = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> find();
							
							if( !empty($oldCreateOrderUserGoodsSpec) ){
								$incGoodsSpecRes = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> setInc('num', $oldData['num']);
								if( !$incGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '更新商品规格总数量失败,请联系管理员');
								}
								$incField = $oldData['delivery_type_id'] == 2 ? 'num3' : 'num2';
								$incGoodsSpecRes = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> setInc($incField, $oldData['num']);
								if( !$incGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '更新商品规格云仓数量失败,请联系管理员');
								}
							}else{
								$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$oldData['goods_id'], 'id'=>$oldData['goods_spec_id'], 'is_delete'=>0]) -> find();
								if( !empty($oldGoodsSpec) ){
									$newGoodsSpec = [];
									$oldGoodsSpec['goods_id'] = $createOrderUserGoods['id'];
									$oldGoodsSpec['num'] = $oldData['num'];
									$oldGoodsSpec['num2'] = in_array($oldData['delivery_type_id'], [3]) ? $oldData['num'] : 0;	//云仓
									$oldGoodsSpec['num3'] = in_array($oldData['delivery_type_id'], [2]) ? $oldData['num'] : 0;	//实仓
									$oldGoodsSpec['create_user_id'] = $oldData['create_user_id'];
									$oldGoodsSpec['parent_id'] = $oldGoodsSpec['id'];
									$oldGoodsSpec['create_user_name'] = $oldData['create_user_name'];
									$oldGoodsSpec['create_user_type'] = $oldData['create_user_type'];
									$oldGoodsSpec['create_date'] = date("Y-m-d H:i:s", time());
									unset($oldGoodsSpec['id']);
									$newGoodsSpec = $oldGoodsSpec;
									$newGoodsSpecRes = Db::table("gd_goods_spec") -> insertGetId($newGoodsSpec);
									if( !$newGoodsSpecRes ) {
										Db::rollback();
										returnResults2('-1', '生成新商品规格失败,请联系管理员');
									}
								}
							}
						}
					}
					
				}
				
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台发货',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台批量提交结算付款（最后付款）
	 */
	public function adminBatchSettlePayment(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> lock(true) -> select();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				foreach ($oldData as $k => $v) {
					if( $v['status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
//					if( $v['overall_status'] != 1 ) returnResults2('-1', '操作失败,订单结算状态有误,请联系管理员');
					if( $v['settle_status'] != 1 ) returnResults2('-1', '操作失败,会计未审核');
				}
				
				Db::startTrans();
				foreach ($oldData as $k => $v) {
//					结算审批状态
					$save['overall_status'] = 1;
					$save['settle_status2'] = 1;
					$save['settle_verify_notes2'] = isset($in['settle_verify_notes2']) ? $in['settle_verify_notes2'] : '';
					$save['settle_verify_user_id2'] = $userInfo['info']['id'];
					$save['settle_verify_user_name2'] = $userInfo['info']['nickname'];
					$save['settle_verify_date2'] = date("Y-m-d H:i:s", time());
					
//					结算打款状态
					$save['payment_verify_status'] = 1;
					$save['payment_verify_commission_rate'] = isset($in['payment_verify_commission_rate']) ? $in['payment_verify_commission_rate'] : 0;
					$save['payment_verify_money'] = $save['payment_verify_commission_rate'] > 0 ? $v['actual_price'] - ($save['payment_verify_commission_rate'] / 100 * $v['actual_price']) : $v['actual_price'];
					$save['payment_verify_user_id'] = $userInfo['info']['id'];
					$save['payment_verify_user_name'] = $userInfo['info']['nickname'];
					$save['payment_verify_date'] = date("Y-m-d H:i:s", time());
					
					$re = Db::table("gd_order") -> where(['id'=>$v['id']]) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '提交失败,请联系管理员');
					}
				}
				Db::commit();
				
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台批量提交结算付款',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 后台批量提交结算审核（第二道审核）
	 */
	public function adminBatchSettleVerify2(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'settle_status2'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> select();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				foreach ($oldData as $k => $v) {
					if( $v['status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
					if( $v['settle_status'] != 1 ) returnResults2('-1', '操作失败,订单结算状态有误,请联系管理员');
					if( $v['settle_status2'] != 3 ) returnResults2('-1', '操作失败,订单结算状态有误,请联系管理员');
				}
				
				if( $in['settle_status2'] == 2 ) $save['overall_status'] = $in['settle_status2'];
				$save['settle_status2'] = $in['settle_status2'];
				$save['settle_verify_notes2'] = isset($in['settle_verify_notes2']) ? $in['settle_verify_notes2'] : '';
				$save['settle_verify_user_id2'] = $userInfo['info']['id'];
				$save['settle_verify_user_name2'] = $userInfo['info']['nickname'];
				$save['settle_verify_date2'] = date("Y-m-d H:i:s", time());
				
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '提交失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台批量提交结算审核（第二道审核）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台批量提交结算审核（第一道审核）
	 */
	public function adminBatchSettleVerify(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'settle_status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> select();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				foreach ($oldData as $k => $v) {
					if( $v['status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
					if( $v['settle_status'] != 3 ) returnResults2('-1', '操作失败,订单结算状态有误,请联系管理员');
				}
				
				if( $in['settle_status'] == 2 ) $save['overall_status'] = $in['settle_status'];
				$save['settle_status'] = $in['settle_status'];
				$save['settle_verify_notes'] = isset($in['settle_verify_notes']) ? $in['settle_verify_notes'] : '';
				$save['settle_verify_user_id'] = $userInfo['info']['id'];
				$save['settle_verify_user_name'] = $userInfo['info']['nickname'];
				$save['settle_verify_date'] = date("Y-m-d H:i:s", time());
				$save['settle_status2'] = $in['settle_status'] == 1 ? 3 : 0;
				
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '提交失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台批量提交结算审核（第一道审核）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 后台批量提交订单结算申请
	 */
	public function adminBatchSettleApplyfor(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'in', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> select();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				foreach ($oldData as $k => $v) {
					if( $v['status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
					if( !in_array($v['overall_status'], [0, 2]) ) returnResults2('-1', '操作失败,订单结算状态有误,请联系管理员');
				}
				
				$save['overall_status'] = 3;
				$save['settle_status'] = 3;
				$save['settle_submit_user_id'] = $userInfo['info']['id'];
				$save['settle_submit_user_name'] = $userInfo['info']['nickname'];
				$save['settle_submit_date'] = date("Y-m-d H:i:s", time());
				
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '提交失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台批量提交订单结算申请',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户修改订单地址
	 */
	public function userEditOrderAddress(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'receiving_address', 'receiving_name', 'receiving_phone'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] != 0 || !in_array($oldData['status'], [0, 2]) ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['receiving_address'] = $in['receiving_address'];
				$save['receiving_name'] = $in['receiving_name'];
				$save['receiving_phone'] = $in['receiving_phone'];
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '修改失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户修改订单地址',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户取消订单
	 */
	public function userCloseOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] != 0 || !in_array($oldData['status'], [0]) ) returnResults2('-1', '操作失败,仅支持取消待付款订单,请联系管理员');
				
				$save['status'] = 6;
				$save['check_date'] = date("Y-m-d H:i:s", time());
				$save['check_user_id'] = $userInfo['info']['id'];
				$save['check_user_name'] = $userInfo['info']['nickname'];
				$save['check_user_type'] = $userInfo['info']['type'];
				
				Db::startTrans();
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '取消失败,请联系管理员');
				}
				
//				查询库存(锁表)
				switch ($oldData['goods_type']) {
					case '3':
//						上架资格
						$orderSubgoodsWhere[] = ['id', 'eq', $oldData['order_subgoods_id']];
						$orderSubgoods = Db::table("gd_order_subgoods") -> where($orderSubgoodsWhere) -> find();
						if( !empty($orderSubgoods) ){
		//					减已购买数量
							$incRe = Db::table("gd_order_subgoods") -> where($orderSubgoodsWhere) -> update(['buy_nums'=>$orderSubgoods['buy_nums'] - $oldData['num']]);
							if( !$incRe ){
								Db::rollback();
								returnResults2('-1', '库存增加失败,请联系管理员');
							}
						}
						break;
					default:
//						普通商品
						$goodsSpecWhere[] = ['id', 'eq', $oldData['goods_spec_id']];
						$goodsSpec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> find();
						if( !empty($goodsSpec) ){
		//					加库存
							$incRe = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> update(['num'=>$goodsSpec['num'] + $oldData['num']]);
							if( !$incRe ){
								Db::rollback();
								returnResults2('-1', '库存增加失败,请联系管理员');
							}
						}
						break;
				}
					
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户取消订单',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户删除订单记录
	 */
	public function userDelOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['status'], [0, 5, 6]) ) returnResults2('-1', '操作失败,仅支持删除已完结的无效订单,请联系管理员');
				
				$save['is_delete'] = 1;
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '删除失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户删除订单记录',
						'business_type'=>2,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	 
	/**
	 * 用户撤销退换货申请
	 */
	public function userRevokeApplyforAftersales(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['refund_applyfor_status'], [1]) ) returnResults2('-1', '操作失败,仅支持撤销售后处理中的申请,请联系管理员');
				
				$save['refund_applyfor_status'] = 9;
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '撤销退换货申请失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户撤销退换货申请',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 用户修改退款金额
	 */
	public function userEditRefundApplyforPrice(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'refund_applyfor_price'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] != 0 || $oldData['refund_applyfor_status'] != 1 ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				$save['refund_applyfor_price'] = $in['refund_applyfor_price'];
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '修改失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户修改退款金额',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户申请售后(退换货)
	 */
	public function userApplyforAftersales(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'refund_type', 'refund_applyfor_price', 'refund_applyfor_reason'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['status'], [3]) ) returnResults2('-1', '操作失败,仅支持对待收货的订单发起售后,请联系管理员');
				
				$save['status'] = 4;
				$save['refund_type'] = $in['refund_type'];
				$save['refund_applyfor_price'] = $in['refund_applyfor_price'];
				$save['refund_applyfor_reason'] = $in['refund_applyfor_reason'];
				$save['refund_applyfor_date'] = date("Y-m-d H:i:s", time());
				$save['refund_applyfor_status'] = 1;
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) returnResults2('-1', '申请售后失败,请联系管理员');
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户申请售后(退换货)',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 计算用户的返佣
	 * @param	$parent_user_id		上级用户id，如果有该参数，直接取值，如果没有该参数，读取下单用户绑定的上级用户
	 */
	public function calculateReward2($orderId, $parent_user_id = 0){
		
		$where['id'] = $orderId;
		$order = Db::table("gd_order") -> where($where) -> find();
		if( empty($order) ) return FALSE;
		
//		下单人
		$orderUser = Db::table("gd_user") -> where(['id'=>$order['create_user_id']]) -> find();
		
//		获取商品分成规则
		$divideIntoConfigGoodsWhere['a.goods_id'] = $order['shop_id'] == 0 ? $order['goods_id'] : $order['parent_goods_id'];
		$divideIntoConfigGoodsWhere['b.delivery_type_config_id'] = $order['delivery_type_id'];
		$divideIntoConfigGoods = Db::table("gd_divide_into_config_goods") -> alias('a') -> join('gd_divide_into_config b', 'a.divide_into_config_id = b.id', 'left') -> field(['a.*']) -> where($divideIntoConfigGoodsWhere) -> find();
		
		if( empty($divideIntoConfigGoods) ){
			$divideIntoConfigWhere['id'] = 1;
		}else{
			$divideIntoConfigWhere['id'] = $divideIntoConfigGoods['divide_into_config_id'];
		}
		$divideIntoConfig = Db::table("gd_divide_into_config") -> where($divideIntoConfigWhere) -> find();
		
//		过滤分成全为0的情况
		if( $divideIntoConfig['value1'] == 0 && $divideIntoConfig['value2'] == 0 && $divideIntoConfig['value3'] == 0 && $divideIntoConfig['value4'] == 0 && $divideIntoConfig['value5'] == 0 ) return FALSE;
//		if( $orderUser['referrer_id'] == 0 && $orderUser['referrer_id2'] == 0 && $orderUser['referrer_id3'] == 0 && $divideIntoConfig['value4'] == 0 ) return FALSE;

//		商家
		if( $orderUser['referrer_id3'] > 0 ){
			$userType3['id'] = $orderUser['referrer_id3'];
		}else{
//			根据收货地址找商家
			$userType3Where['type'] = 3;
			$userType3Where['province'] = $order['receiving_province'];
			$userType3Where['city'] = $order['receiving_city'];
			$userType3Where['area'] = $order['receiving_area'];
			$userType3 = Db::table("gd_user") -> where($userType3Where) -> find();
		}
		
//		代理商
		if( $orderUser['referrer_id6'] > 0 ){
			$userType6['id'] = $orderUser['referrer_id6'];
		}else{
//			根据收货地址找代理商
			$userType6Where['type'] = 6;
			$userType6Where['province'] = $order['receiving_province'];
			$userType6Where['city'] = $order['receiving_city'];
			$userType6Where['area'] = $order['receiving_area'];
			$userType6 = Db::table("gd_user") -> where($userType6Where) -> find();
		}
		
		$reward = [];
//		推荐人
		$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value1'] : ($order['total_price'] * ($divideIntoConfig['value1'] / 100));
//		if( isset($parent_user_id) && !empty($parent_user_id) && $parent_user_id  > 0){
		if( $orderUser['referrer_id'] == 0 ){
			$reward[] = [
				'user_id' => '-1',
				'rewards' => $money,
			];
		}else{
			if( $orderUser['referrer_id'] != 0 && $divideIntoConfig['value1'] != 0 ) {
				$reward[] = [
					'user_id' => $orderUser['referrer_id'],
					'rewards' => $money,
				];
			}
		}
//		商家
		if( !empty($userType3) ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value5'] : ($order['total_price'] * ($divideIntoConfig['value5'] / 100));
			$reward[] = [
				'user_id' => $userType3['id'],
				'rewards' => $money,
			];
		}
//		代理商
		if( !empty($userType6) ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value3'] : ($order['total_price'] * ($divideIntoConfig['value3'] / 100));
			$reward[] = [
				'user_id' => $userType6['id'],
				'rewards' => $money,
			];
		}
//		居间商(代理商的上级)
//		if( !empty($userType6) && $userType6['referrer_id'] > 0 ) {
//			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value2'] : ($order['total_price'] * ($divideIntoConfig['value2'] / 100));
//			$reward[] = [
//				'user_id' => $userType6['referrer_id'],
//				'rewards' => $money,
//			];
//		}
//		总平台
		if( $divideIntoConfig['value4'] != 0 ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value4'] : ($order['total_price'] * ($divideIntoConfig['value4'] / 100));
			$reward[] = [
				'user_id' => 1,
				'rewards' => $money,
			];
		}
		return $reward;
	}
	
	/**
	 * 计算用户的返佣
	 * @param	$parent_user_id		上级用户id，如果有该参数，直接取值，如果没有该参数，读取下单用户绑定的上级用户
	 */
	public function calculateReward($orderId, $parent_user_id = 0){
		
		$where['id'] = $orderId;
		$order = Db::table("gd_order") -> where($where) -> find();
		if( empty($order) ) return FALSE;
		
//		下单人
		$orderUser = Db::table("gd_user") -> where(['id'=>$order['create_user_id']]) -> find();
		
//		获取商品分成规则
		$divideIntoConfigGoodsWhere['goods_id'] = $order['goods_id'];
		$divideIntoConfigGoods = Db::table("gd_divide_into_config_goods") -> where($divideIntoConfigGoodsWhere) -> find();
		if( empty($divideIntoConfigGoods) ){
			$divideIntoConfigWhere['id'] = 1;
		}else{
			$divideIntoConfigWhere['id'] = $divideIntoConfigGoods['divide_into_config_id'];
		}
		$divideIntoConfig = Db::table("gd_divide_into_config") -> where($divideIntoConfigWhere) -> find();
		
//		if( $orderUser['referrer_id'] == 0 && $orderUser['referrer_id2'] == 0 && $orderUser['referrer_id3'] == 0 && $divideIntoConfig['value4'] == 0 ) return FALSE;

//		根据收货地址找代理商
		$userType6Where['type'] = 6;
		$userType6Where['province'] = $order['receiving_province'];
		$userType6Where['city'] = $order['receiving_city'];
		$userType6Where['area'] = $order['receiving_area'];
		$userType6 = Db::table("gd_user") -> where($userType6Where) -> find();
		
		$reward = [];
//		推荐人
		$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value1'] : ($order['total_price'] * ($divideIntoConfig['value1'] / 100));
		if( isset($parent_user_id) && !empty($parent_user_id) && $parent_user_id  > 0){
			$reward[] = [
				'user_id' => $parent_user_id,
				'rewards' => $money,
			];
		}else{
			if( $orderUser['referrer_id'] != 0 && $divideIntoConfig['value1'] != 0 ) {
				$reward[] = [
					'user_id' => $orderUser['referrer_id'],
					'rewards' => $money,
				];
			}
		}
//		代理商
		if( !empty($userType6) ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value3'] : ($order['total_price'] * ($divideIntoConfig['value3'] / 100));
			$reward[] = [
				'user_id' => $userType6['id'],
				'rewards' => $money,
			];
		}
//		居间商(代理商的上级)
		if( !empty($userType6) && $userType6['referrer_id'] > 0 ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value2'] : ($order['total_price'] * ($divideIntoConfig['value2'] / 100));
			$reward[] = [
				'user_id' => $userType6['referrer_id'],
				'rewards' => $money,
			];
		}
//		总平台
		if( $divideIntoConfig['value4'] != 0 ) {
			$money = $divideIntoConfig['type'] == 1 ? $divideIntoConfig['value4'] : ($order['total_price'] * ($divideIntoConfig['value4'] / 100));
			$reward[] = [
				'user_id' => 1,
				'rewards' => $money,
			];
		}
		return $reward;
	}
	
	/**
	 * 用户确认收货
	 */
	public function userCheckOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['status'], [11]) ) returnResults2('-1', '操作失败,订单状态有误,请联系管理员');
				
				Db::startTrans();
				
				$save['status'] = 1;
				$save['check_date'] = date("Y-m-d H:i:s", time());
				$save['check_user_id'] = $userInfo['info']['id'];
				$save['check_user_name'] = $userInfo['info']['nickname'];
				$save['check_user_type'] = $userInfo['info']['type'];
				$re = Db::table("gd_order") -> where($where) -> update($save);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '确认收货失败,请联系管理员');
				}
				
//				处理订单各级返佣
//				$oldReward = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> select();
//				if( !empty($oldReward) ){
////					变更奖励为生效
//					$res = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> update(['withdrawal_status'=>'0']);
//					if( !$res ){
//						Db::rollback();
//						returnResults2('-1', '变更奖励状态失败,请联系管理员');
//					}
//					
////					给用户账号加余额
//					foreach ($oldReward as $k => $v) {
//						if( $v['rewards'] > 0 ) {
//							$re1 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('rebate', $v['rewards']);
//							$re2 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('total_income', $v['rewards']);
//							if( !$re1 || !$re2 ) {
//								Db::rollback();
//								returnResults2('-1', '变更用户信息失败,请联系管理员');
//							}
//						}
//					}
//				}
				
//				处理下单人的积分
				$newData['num'] = $oldData['actual_price'];
				$newData['type'] = 1;
				$newData['integral_user_id'] = $in['user_id'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_user_type'] = $userInfo['info']['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$re = Db::table("gd_user_integral") -> insertGetId($newData);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '生成积分明细失败,请联系管理员');
				}
				
				$re = Db::table("gd_user") -> where(['id'=>$userInfo['info']['id']]) -> setInc('integral', $newData['num']);
				if( !$re ) {
					Db::rollback();
					returnResults2('-1', '变更用户积分失败,请联系管理员');
				}
				
				
//				处理商家进货订单库存
				if( $oldData['source'] == 21 && in_array($oldData['delivery_type_id'], [2, 3]) ){
//					读取原商品
					$oldGoods = Db::table("gd_goods") -> where(['id'=>$oldData['goods_id']]) -> find();
					if( !empty($oldGoods) ){
						$createOrderUserGoods = Db::table("gd_goods") -> where(['parent_id'=>$oldData['goods_id'], 'create_user_id'=>$oldData['create_user_id'], 'is_delete'=>0]) -> find();
						if( empty($createOrderUserGoods) ){
//							生成子商品
							$subGoods = $oldGoods;
							unset($subGoods['id']);
							$shop = Db::table("gd_shop") -> where(['create_user_id'=>$oldData['create_user_id']]) -> find();
							$subGoods['label'] = '';
							$subGoods['shop_id'] = empty($shop) ? 0 : $shop['id'];
							$subGoods['parent_id'] = $oldGoods['id'];
							$subGoods['create_user_id'] = $oldData['create_user_id'];
							$subGoods['create_user_name'] = $oldData['create_user_name'];
							$subGoods['create_user_type'] = $oldData['create_user_type'];
							$subGoods['create_date'] = date("Y-m-d H:i:s", time());
							$newGoodsId = Db::table("gd_goods") -> insertGetId($subGoods);
							if( !$newGoodsId ) {
								Db::rollback();
								returnResults2('-1', '生成新商品失败,请联系管理员');
							}
							
							$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$oldData['goods_id'], 'is_delete'=>0]) -> select();
							if( !empty($oldGoodsSpec) ){
								$newGoodsSpec = [];
								foreach ($oldGoodsSpec as $k => $v) {
									$v['goods_id'] = $newGoodsId;
									$v['num'] = $oldData['goods_spec_id'] == $v['id'] ? $oldData['num'] : 0;
									$v['num2'] = $oldData['goods_spec_id'] == $v['id'] && in_array($oldData['delivery_type_id'], [2]) ? $oldData['num'] : 0;	//实仓
									$v['num3'] = $oldData['goods_spec_id'] == $v['id'] && in_array($oldData['delivery_type_id'], [3]) ? $oldData['num'] : 0;	//云仓															//实仓
									$v['create_user_id'] = $oldData['create_user_id'];
									$v['parent_id'] = $v['id'];
									$v['create_user_name'] = $oldData['create_user_name'];
									$v['create_user_type'] = $oldData['create_user_type'];
									$v['create_date'] = date("Y-m-d H:i:s", time());
									unset($v['id']);
									$newGoodsSpec[$k] = $v;
								}
								$newGoodsSpecRes = Db::table("gd_goods_spec") -> insertAll($newGoodsSpec);
								if( !$newGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '生成新商品规格失败,请联系管理员');
								}
							}
						}else{
							$createOrderUserGoodsSpecWhere['goods_id'] = $createOrderUserGoods['id'];
							$createOrderUserGoodsSpecWhere['parent_id'] = $oldData['goods_spec_id'];
							$createOrderUserGoodsSpecWhere['create_user_id'] = $oldData['create_user_id'];
							$oldCreateOrderUserGoodsSpec = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> find();
							
							if( !empty($oldCreateOrderUserGoodsSpec) ){
								$incGoodsSpecRes = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> setInc('num', $oldData['num']);
								if( !$incGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '更新商品规格总数量失败,请联系管理员');
								}
								$incGoodsSpecRes = Db::table("gd_goods_spec") -> where($createOrderUserGoodsSpecWhere) -> setInc('num2', $oldData['num']);
								if( !$incGoodsSpecRes ) {
									Db::rollback();
									returnResults2('-1', '更新商品规格云仓数量失败,请联系管理员');
								}
							}else{
								$oldGoodsSpec = Db::table("gd_goods_spec") -> where(['goods_id'=>$oldData['goods_id'], 'id'=>$oldData['goods_spec_id'], 'is_delete'=>0]) -> find();
								if( !empty($oldGoodsSpec) ){
									$newGoodsSpec = [];
									$oldGoodsSpec['goods_id'] = $createOrderUserGoods['id'];
									$oldGoodsSpec['num'] = $oldData['num'];
									$oldGoodsSpec['num2'] = in_array($oldData['delivery_type_id'], [2]) ? $oldData['num'] : 0;	//实仓
									$oldGoodsSpec['num3'] = in_array($oldData['delivery_type_id'], [3]) ? $oldData['num'] : 0;	//云仓
									$oldGoodsSpec['create_user_id'] = $oldData['create_user_id'];
									$oldGoodsSpec['parent_id'] = $oldGoodsSpec['id'];
									$oldGoodsSpec['create_user_name'] = $oldData['create_user_name'];
									$oldGoodsSpec['create_user_type'] = $oldData['create_user_type'];
									$oldGoodsSpec['create_date'] = date("Y-m-d H:i:s", time());
									unset($oldGoodsSpec['id']);
									$newGoodsSpec = $oldGoodsSpec;
									$newGoodsSpecRes = Db::table("gd_goods_spec") -> insertGetId($newGoodsSpec);
									if( !$newGoodsSpecRes ) {
										Db::rollback();
										returnResults2('-1', '生成新商品规格失败,请联系管理员');
									}
								}
							}
						}
					}
					
				}
				
//				确认收货，处理下单人上级关系
				if( isset($oldData['parent_user_id']) && $oldData['parent_user_id'] > 0 ){
//					订单下单人没绑定任何上级
					if( $userInfo['info']['referrer_id'] == 0 && $userInfo['info']['referrer_id3'] == 0 && $userInfo['info']['referrer_id6'] == 0 ){
//						读取订单推荐人数据
						$parentUserInfo = Db::table("gd_user") -> where(['id'=>$oldData['parent_user_id']]) -> find();
						
//						下单人未绑定上级，自动绑定
						$saveCreateOrderUser2['referrer_id'] = $parentUserInfo['id'];
						$saveCreateOrderUser2['referrer_id3'] = $parentUserInfo['referrer_id3'];
						$saveCreateOrderUser2['referrer_id6'] = $parentUserInfo['referrer_id6'];
						$saveCreateOrderUser2Re = Db::table("gd_user") -> where(['id'=>$oldData['create_user_id']]) -> update($saveCreateOrderUser2);
						if( !$saveCreateOrderUser2Re ){
							Db::rollback();
							returnResults2('-1', '绑定下单人上级关系失败,请联系管理员');
						}
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'用户确认收货',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户付款
	 */
	
	/**
	 * 后台关闭订单
	 */
	public function adminCloseOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['status'], [0]) ) returnResults2('-1', '操作失败,仅支持关闭待付款的订单');
				
				$save['status'] = 7;
				$save['check_date'] = date("Y-m-d H:i:s", time());
				$save['check_user_id'] = $userInfo['info']['id'];
				$save['check_user_name'] = $userInfo['info']['nickname'];
				$save['check_user_type'] = $userInfo['info']['type'];
				$save = filterArr($save, array_keys($save), $oldData);
				
				Db::startTrans();
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '后台关闭订单,请联系管理员');
					}
				}
				
//				查询库存
				$goodsSpecWhere[] = ['id', 'eq', $oldData['goods_spec_id']];
				$goodsSpec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> find();
				if( !empty($goodsSpec) ){
//					加库存
					$incRe = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> update(['num'=>$goodsSpec['num'] + $oldData['num']]);
					if( !$incRe ){
						Db::rollback();
						returnResults2('-1', '库存增加失败,请联系管理员');
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台关闭订单',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 后台改价
	 */
	public function adminEditPrice(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id', 'total_price'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults2('-1', '操作失败,原订单有误,请联系管理员');
				if( $oldData['is_delete'] == 1 || !in_array($oldData['status'], [0]) ) returnResults2('-1', '操作失败,仅支持更改待付款的订单价格');
				
				$save['total_price'] = $in['total_price'];
				$save = filterArr($save, array_keys($save), $oldData);
				
				if( !empty($save) ){
					$re = Db::table("gd_order") -> where($where) -> update($save);
					if( !$re ) returnResults2('-1', '后台改价失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台改价',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 详情
	 */
	public function details(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['id']];
				
				$data = Db::table("gd_order") -> where($where) -> find();
				
				if( !empty($data) ) {
					$data['goods'] = Db::table("gd_goods") -> where(['id'=>$data['goods_id']]) -> find();
					$data['goodsSpec'] = Db::table("gd_goods_spec") -> where(['id'=>$data['goods_spec_id']]) -> find();
					$data['paymentRecords'] = Db::table("gd_payment_records") -> where(['order_id'=>$data['id'], 'pay_status'=>1]) -> find();
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取订单详情',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 列表
	 */
	public function index2(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				if( isset($in['refund_applyfor_status']) && !is_array($in['refund_applyfor_status']) ) {
					$refund_applyfor_status = $in['refund_applyfor_status'];
					$in['refund_applyfor_status'] = [$refund_applyfor_status];
				}
				if( isset($in['shop_id']) && !is_array($in['shop_id']) ){
					$in['shop_id'] = [$in['shop_id']];
				}
				
				$where[] = ['is_delete', 'eq', 0];
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['check_date']) ) $where[] = ['check_date', 'between', $in['check_date']];
//				if( isset($in['order_type']) ) $where[] = ['order_type', 'eq', $in['order_type']];
				if( isset($in['status']) ) $where[] = ['status', 'in', $in['status']];
				if( isset($in['source']) ) $where[] = ['source', 'in', $in['source']];
				if( isset($in['settle_status']) ) $where[] = ['settle_status', 'in', $in['settle_status']];
				if( isset($in['settle_status2']) ) $where[] = ['settle_status2', 'in', $in['settle_status2']];
				if( isset($in['payment_verify_status']) ) $where[] = ['payment_verify_status', 'in', $in['payment_verify_status']];
				if( isset($in['create_user_name']) ) $where[] = ['create_user_name', 'like', '%'.$in['create_user_name'].'%'];
				if( isset($in['goods_create_user_shop_name']) ) $where[] = ['goods_create_user_shop_name', 'like', '%'.$in['goods_create_user_shop_name'].'%'];
				if( isset($in['receiving_name']) ) $where[] = ['receiving_name', 'like', '%'.$in['receiving_name'].'%'];
				if( isset($in['goods_create_user_name']) ) $where[] = ['goods_create_user_name', 'like', '%'.$in['goods_create_user_name'].'%'];
				if( isset($in['code']) ) $where[] = ['code', 'like', '%'.$in['code'].'%'];
				if( isset($in['shop_id']) ) $where[] = ['shop_id', 'in', $in['shop_id']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['refund_applyfor_status']) ) $where[] = ['refund_applyfor_status', 'in', $in['refund_applyfor_status']];
				if( isset($in['goods_type']) ) $where[] = ['goods_type', 'eq', trim($in['goods_type'])];
				if( isset($in['write_off_status']) ) $where[] = ['write_off_status', 'eq', trim($in['write_off_status'])];
				if( isset($in['goods_create_user_id']) ) $where[] = ['goods_create_user_id', 'eq', trim($in['goods_create_user_id'])];
				if( isset($in['receiving_province']) ) $where[] = ['receiving_province', 'eq', trim($in['receiving_province'])];
				if( isset($in['receiving_city']) ) $where[] = ['receiving_city', 'eq', trim($in['receiving_city'])];
				if( isset($in['receiving_area']) ) $where[] = ['receiving_area', 'eq', trim($in['receiving_area'])];
				if( isset($in['overall_status']) ) $where[] = ['overall_status', 'eq', trim($in['overall_status'])];
				if( isset($in['isSendOrder']) && $in['isSendOrder'] == 1 ){
					$where[] = ['status', 'gt', 0];
					$where[] = ['send_goods_date', 'gt', '0000-00-00 00:00:00'];
				}
				if( isset($in['order_type']) && !empty($in['order_type']) ) {
					if( $in['order_type'] == 1 ) $where[] = ['shop_id', 'eq', 0];			//自营
					if( $in['order_type'] == 2 ) $where[] = ['shop_id', 'gt', 0];			//商户
					if( $in['order_type'] == 3 ) $where[] = ['order_type', 'eq', 3];		//寄售
					unset($in['order_type']);
				}
				if( isset($in['withdrawalStatus']) && !empty($in['withdrawalStatus']) ){
					switch ($in['withdrawalStatus']) {
						case '0': $where[] = ['settle_status|settle_status2', 'eq', 0]; break;
						case '1': 
							$where[] = ['settle_status', 'eq', 1];
							$where[] = ['settle_status2', 'eq', 1];
							break;
						case '2': $where[] = ['settle_status|settle_status2', 'eq', 2]; break;
					}
				}
				
				$data = Db::table("gd_order") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_order") -> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$data[$k]['totalWriteoffNums'] = 0;		//需要核销的总数量
						$data[$k]['writeoffNums1'] = 0;			//已核销数
						$data[$k]['writeoffNums0'] = 0;			//未核销数
						$data[$k]['delivery_type_price'] = 0;	//总平台抽佣金额
						
						if( $v['source'] == 21 ){
//							商家进货
							$data[$k]['delivery_type_price'] = round($v['total_price'] * ($v['delivery_type_rate'] / 100), 2);
//							$data[$k]['total_price'] = $v['total_price'] * $v['delivery_type_rate3'];
						}
						
						if( $v['goods_type'] == 2 ){
							$data[$k]['totalWriteoffNums'] = $v['num'] * $v['goods_nums'];
							$data[$k]['writeoffNums1'] = Db::table("gd_order_writeoff") -> where(['order_id'=>$v['id']]) -> sum("nums");
							$data[$k]['writeoffNums0'] = $data[$k]['totalWriteoffNums'] - $data[$k]['writeoffNums1'];
						}
						
						$data[$k]['goods'] = Db::table("gd_goods") -> where(['id'=>$v['goods_id']]) -> find();
						$data[$k]['goodsSpec'] = Db::table("gd_goods_spec") -> where(['id'=>$v['goods_spec_id']]) -> find();
						$settleCreateUserShopInfo = Db::table("gd_shop") -> where(['create_user_id'=>$v['settle_submit_user_id']]) -> find();
						$createGoodsShopInfo = Db::table("gd_shop") -> where(['id'=>$v['shop_id']]) -> find();
						
//						创建商品的商户信息
						$data[$k]['createGoodsShopName'] = empty($createGoodsShopInfo) ? $v['goods_create_user_name'] : $createGoodsShopInfo['name'];
						$data[$k]['createGoodsShopPhone'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['phone'];
						$data[$k]['createGoodsShopBank'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['bank'];
						$data[$k]['createGoodsShopBankCardNo'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['bank_card_no'];
						$data[$k]['createGoodsShopBackAccount'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['back_account'];
						
//						提交结算用户的商店信息
						$data[$k]['settleCreateUserShopName'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['name'];
						$data[$k]['settleCreateUserShopPhone'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['phone'];
						$data[$k]['settleCreateUserShopBank'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['bank'];
						$data[$k]['settleCreateUserShopBankCardNo'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['bank_card_no'];
						$data[$k]['settleCreateUserShopBackAccount'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['back_account'];
//						提交结算用户历史已通过的结算金额
						$data[$k]['settleCreateUserHistorySettleMoney'] = Db::table("gd_order") -> where([
							['settle_submit_user_id', 'eq', $v['settle_submit_user_id']],
							['id', 'neq', $v['id']],
							['settle_status', 'eq', 1],
						]) -> sum('payment_verify_money');
						if( $v['shop_id'] == 0 ) $data[$k]['orderTypeStr'] = '自营';
						if( $v['shop_id'] > 0 ) $data[$k]['orderTypeStr'] = '商户';
						if( $v['order_type'] == 3 ) $data[$k]['orderTypeStr'] =  $data[$k]['orderTypeStr'] . '(寄售)';
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取订单列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 列表
	 */
	public function index(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$num = isset($in['num']) ? $in['num'] : 20;
				$start = isset($in['page']) && $in['page'] > 0 ? (($in['page'] - 1) * $num) : 0;
				
				if( isset($in['refund_applyfor_status']) && !is_array($in['refund_applyfor_status']) ) {
					$refund_applyfor_status = $in['refund_applyfor_status'];
					$in['refund_applyfor_status'] = [$refund_applyfor_status];
				}
				
				$where[] = ['is_delete', 'eq', 0];
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'STORE' ) $where[] = ['shop_id', 'eq', $userInfo['shop']['id']];						//商家
				if( isset($userInfo['auth_group']) && $userInfo['auth_group']['path'] == 'REGION' ) {																			//代理商
					$where[] = ['receiving_province', 'eq', $userInfo['info']['province']];
					$where[] = ['receiving_city', 'eq', $userInfo['info']['city']];
					$where[] = ['receiving_area', 'eq', $userInfo['info']['area']];
				}
				if( isset($in['create_date']) ) $where[] = ['create_date', 'between', $in['create_date']];
				if( isset($in['check_date']) ) $where[] = ['check_date', 'between', $in['check_date']];
//				if( isset($in['order_type']) ) $where[] = ['order_type', 'eq', $in['order_type']];
				if( isset($in['status']) ) $where[] = ['status', 'in', $in['status']];
				if( isset($in['settle_status']) ) $where[] = ['settle_status', 'in', $in['settle_status']];
				if( isset($in['settle_status2']) ) $where[] = ['settle_status2', 'in', $in['settle_status2']];
				if( isset($in['payment_verify_status']) ) $where[] = ['payment_verify_status', 'in', $in['payment_verify_status']];
				if( isset($in['create_user_name']) ) $where[] = ['create_user_name', 'like', '%'.$in['create_user_name'].'%'];
				if( isset($in['goods_create_user_shop_name']) ) $where[] = ['goods_create_user_shop_name', 'like', '%'.$in['goods_create_user_shop_name'].'%'];
				if( isset($in['receiving_name']) ) $where[] = ['receiving_name', 'like', '%'.$in['receiving_name'].'%'];
				if( isset($in['goods_create_user_name']) ) $where[] = ['goods_create_user_name', 'like', '%'.$in['goods_create_user_name'].'%'];
				if( isset($in['code']) ) $where[] = ['code', 'like', '%'.$in['code'].'%'];
				if( isset($in['shop_id']) ) $where[] = ['shop_id', 'eq', $in['shop_id']];
				if( isset($in['create_user_id']) ) $where[] = ['create_user_id', 'eq', $in['create_user_id']];
				if( isset($in['refund_applyfor_status']) ) $where[] = ['refund_applyfor_status', 'in', $in['refund_applyfor_status']];
				if( isset($in['goods_type']) ) $where[] = ['goods_type', 'eq', trim($in['goods_type'])];
				if( isset($in['write_off_status']) ) $where[] = ['write_off_status', 'eq', trim($in['write_off_status'])];
				if( isset($in['goods_create_user_id']) ) $where[] = ['goods_create_user_id', 'eq', trim($in['goods_create_user_id'])];
				if( isset($in['receiving_province']) ) $where[] = ['receiving_province', 'eq', trim($in['receiving_province'])];
				if( isset($in['receiving_city']) ) $where[] = ['receiving_city', 'eq', trim($in['receiving_city'])];
				if( isset($in['receiving_area']) ) $where[] = ['receiving_area', 'eq', trim($in['receiving_area'])];
				if( isset($in['overall_status']) ) $where[] = ['overall_status', 'eq', trim($in['overall_status'])];
				if( isset($in['source']) && is_array($in['source']) ) $where[] = ['source', 'in', $in['source']];
				if( isset($in['source']) && !is_array($in['source']) ) $where[] = ['source', 'eq', trim($in['source'])];
				if( isset($in['isSendOrder']) && $in['isSendOrder'] == 1 ){
					$where[] = ['status', 'gt', 0];
					$where[] = ['send_goods_date', 'gt', '0000-00-00 00:00:00'];
				}
				if( isset($in['order_type']) && !empty($in['order_type']) ) {
					if( $in['order_type'] == 1 ) $where[] = ['shop_id', 'eq', 0];			//自营
					if( $in['order_type'] == 2 ) $where[] = ['shop_id', 'gt', 0];			//商户
					if( $in['order_type'] == 3 ) $where[] = ['order_type', 'eq', 3];		//寄售
					unset($in['order_type']);
				}
				if( isset($in['withdrawalStatus']) && !empty($in['withdrawalStatus']) ){
					switch ($in['withdrawalStatus']) {
						case '0': $where[] = ['settle_status|settle_status2', 'eq', 0]; break;
						case '1': 
							$where[] = ['settle_status', 'eq', 1];
							$where[] = ['settle_status2', 'eq', 1];
							break;
						case '2': $where[] = ['settle_status|settle_status2', 'eq', 2]; break;
					}
				}
				
				$data = Db::table("gd_order") -> where($where) -> order("id desc") -> limit($start, $num) -> select();
				$count = Db::table("gd_order") -> where($where) -> count();
				
				if( !empty($data) ){
					foreach ($data as $k => $v) {
						$data[$k]['totalWriteoffNums'] = 0;		//需要核销的总数量
						$data[$k]['writeoffNums1'] = 0;			//已核销数
						$data[$k]['writeoffNums0'] = 0;			//未核销数
						$data[$k]['delivery_type_price'] = 0;	//总平台抽佣金额
						
						if( $v['source'] == 21 ){
//							商家进货
							$data[$k]['delivery_type_price'] = round($v['total_price'] * ($v['delivery_type_rate'] / 100), 2);
//							$data[$k]['total_price'] = $v['total_price'] * $v['delivery_type_rate3'];
						}
						
						if( $v['goods_type'] == 2 ){
							$data[$k]['totalWriteoffNums'] = $v['num'] * $v['goods_nums'];
							$data[$k]['writeoffNums1'] = Db::table("gd_order_writeoff") -> where(['order_id'=>$v['id']]) -> sum("nums");
							$data[$k]['writeoffNums0'] = $data[$k]['totalWriteoffNums'] - $data[$k]['writeoffNums1'];
						}
						
						$data[$k]['goods'] = Db::table("gd_goods") -> where(['id'=>$v['goods_id']]) -> find();
						$data[$k]['goodsSpec'] = Db::table("gd_goods_spec") -> where(['id'=>$v['goods_spec_id']]) -> find();
						$settleCreateUserShopInfo = Db::table("gd_shop") -> where(['create_user_id'=>$v['settle_submit_user_id']]) -> find();
						$createGoodsShopInfo = Db::table("gd_shop") -> where(['id'=>$v['shop_id']]) -> find();
						
//						创建商品的商户信息
						$data[$k]['createGoodsShopName'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['name'];
						$data[$k]['createGoodsShopPhone'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['phone'];
						$data[$k]['createGoodsShopBank'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['bank'];
						$data[$k]['createGoodsShopBankCardNo'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['bank_card_no'];
						$data[$k]['createGoodsShopBackAccount'] = empty($createGoodsShopInfo) ? '' : $createGoodsShopInfo['back_account'];
						
//						提交结算用户的商店信息
						$data[$k]['settleCreateUserShopName'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['name'];
						$data[$k]['settleCreateUserShopPhone'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['phone'];
						$data[$k]['settleCreateUserShopBank'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['bank'];
						$data[$k]['settleCreateUserShopBankCardNo'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['bank_card_no'];
						$data[$k]['settleCreateUserShopBackAccount'] = empty($settleCreateUserShopInfo) ? '' : $settleCreateUserShopInfo['back_account'];
//						提交结算用户历史已通过的结算金额
						$data[$k]['settleCreateUserHistorySettleMoney'] = Db::table("gd_order") -> where([
							['settle_submit_user_id', 'eq', $v['settle_submit_user_id']],
							['id', 'neq', $v['id']],
							['settle_status', 'eq', 1],
						]) -> sum('payment_verify_money');
						if( $v['shop_id'] == 0 ) $data[$k]['orderTypeStr'] = '自营';
						if( $v['shop_id'] > 0 ) $data[$k]['orderTypeStr'] = '商户';
						if( $v['order_type'] == 3 ) $data[$k]['orderTypeStr'] =  $data[$k]['orderTypeStr'] . '(寄售)';
					}
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $data;
				$outArr['totalNums'] = $count;				
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'获取订单列表',
						'business_type'=>4,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 编辑
	 */
//	public function edit(){
//		if(request() -> isPost()){
//			$in = input("post.");
//			$bool = is_empty(['user_id', 'id'], $in);
//			if($bool){
//				$outArr['code'] = '40004';
//			}else{
//				$userInfo = $this -> getUserInfo();
//				
//				$where[] = ['id', 'eq', $in['id']];
//				$oldData = Db::table("gd_address") -> where($where) -> find();
//				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
//				
//				$save = [];
//				foreach ($in as $k => $v) {
//					if( !in_array($k, ['id', 'user_id']) ){
//						$save[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_SLASHES) : $v;
//					}
//				}
//				
//				$save = filterArr($save, array_keys($save), $oldData);
//				
//				if( !empty($save) ){
//					$re = Db::table("gd_address") -> where($where) -> update($save);
//					if( !$re ) returnResults2('-1', '编辑失败,请联系管理员');
//				}
//				$outArr['code'] = '1';
//				
////				写入操作日志
//				$old_data_json = $oldData;
//				controller("service/OperLog") -> logs(
//					[
//						'title'=>'编辑地址',
//						'business_type'=>3,
//						'oper_name'=>$userInfo['info']['nickname'],
//						'oper_user_id'=>$userInfo['info']['id'],
//						'json'=>[
//							[
//								'json_result'=>$outArr,
//								'old_data'=> isset($old_data_json) ? $old_data_json : [],
//							]
//						]
//					]
//				);
//			}
//		}else{
//			$outArr['code'] = '50001';
//		}
//		returnResults($outArr);
//	}

	/**
	 * 后台改变订单状态
	 */
	public function adminEditOrderStatus(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'order_id', 'status'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['order_id']];
				$oldData = Db::table("gd_order") -> where($where) -> find();
				if( empty($oldData) ) returnResults(['code'=>'-1', 'msg'=>'原数据有误']);
				
//				订单状态（0：待付款，1：已完成，2：待发货，3：已收货，4：待退款(售后已同意)，5：已退款，6：用户取消， 7：后台关单，8：已送达，9：已签收，10：已退回，11：已发货，12：已核销）
				$save = [];
				switch ($in['status']) {
//					代用户确认收货
					case '1':
						$save['status'] = $in['status'];
						$save['check_date'] = date("Y-m-d H:i:s", time());
						$save['check_user_id'] = $userInfo['info']['id'];
						$save['check_user_name'] = $userInfo['info']['nickname'];
						$save['check_user_type'] = $userInfo['info']['type'];
						
						Db::startTrans();
						$re = Db::table("gd_order") -> where($where) -> update($save);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '确认收货失败,请联系管理员');
						}
						
//						处理订单各级返佣
//						$oldReward = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> select();
//						if( !empty($oldReward) ){
////							变更奖励为生效
//							$res = Db::table("gd_reward") -> where(['order_id'=>$oldData['id'], 'withdrawal_status'=>'-1']) -> update(['withdrawal_status'=>'0']);
//							if( !$res ){
//								Db::rollback();
//								returnResults2('-1', '变更奖励状态失败,请联系管理员');
//							}
//							
////							给用户账号加余额
//							foreach ($oldReward as $k => $v) {
//								if( $v['rewards'] > 0 ) {
//									$re1 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('rebate', $v['rewards']);
//									$re2 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('total_income', $v['rewards']);
//									if( !$re1 || !$re2 ) {
//										Db::rollback();
//										returnResults2('-1', '变更用户信息失败,请联系管理员');
//									}
//								}
//							}
//						}
						
//						处理下单人的积分
						$newData['num'] = $oldData['actual_price'];
						$newData['type'] = 1;
						$newData['integral_user_id'] = $oldData['create_user_id'];
						$newData['create_user_id'] = $oldData['create_user_id'];
						$newData['create_user_name'] = $oldData['create_user_name'];
						$newData['create_user_type'] = $oldData['create_user_type'];
						$newData['create_date'] = date("Y-m-d H:i:s", time());
						$re = Db::table("gd_user_integral") -> insertGetId($newData);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '生成积分明细失败,请联系管理员');
						}
						
						$re = Db::table("gd_user") -> where(['id'=>$oldData['create_user_id']]) -> setInc('integral', $newData['num']);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '变更用户积分失败,请联系管理员');
						}
						
//						确认收货，处理下单人上级关系
						if( isset($oldData['parent_user_id']) && $oldData['parent_user_id'] > 0 ){
							$createOrderUserInfo = Db::table("gd_user") -> where(['id'=>$oldData['create_user_id']]) -> find();
							
//							订单下单人没绑定任何上级
							if( $createOrderUserInfo['referrer_id'] == 0 && $createOrderUserInfo['referrer_id3'] == 0 && $createOrderUserInfo['referrer_id6'] == 0 ){
//								读取订单推荐人数据
								$parentUserInfo = Db::table("gd_user") -> where(['id'=>$oldData['parent_user_id']]) -> find();
						
//								下单人未绑定上级，自动绑定
								$saveCreateOrderUser2['referrer_id'] = $parentUserInfo['id'];
								$saveCreateOrderUser2['referrer_id3'] = $parentUserInfo['referrer_id3'];
								$saveCreateOrderUser2['referrer_id6'] = $parentUserInfo['referrer_id6'];
								$saveCreateOrderUser2Re = Db::table("gd_user") -> where(['id'=>$oldData['create_user_id']]) -> update($saveCreateOrderUser2);
								if( !$saveCreateOrderUser2Re ){
									Db::rollback();
									returnResults2('-1', '绑定下单人上级关系失败,请联系管理员');
								}
							}
						}
						
						Db::commit();
						break;
				}
				
				$outArr['code'] = '1';
				
//				写入操作日志
				$old_data_json = $oldData;
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台改变订单状态',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 后台新增订单（主订单）
	 */
	public function adminAddOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'goods_id', 'goods_spec_id', 'num', 'total_price', 'create_order_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['goods_id']];
				$goods = Db::table("gd_goods") -> where($where) -> find();
				
				$createGoodsShop = Db::table("gd_shop") -> where(['create_user_id'=>$goods['create_user_id']]) -> find();
				
				$village = [];
				if( isset($in['village_id']) && $in['village_id'] > 0 ){
					$village = Db::table("gd_village") -> where(['id'=>$in['village_id']]) -> find();
				}
				
				$createOrderUserInfo = [];
				if( isset($in['create_order_user_id']) ){
					$createOrderUserInfo = Db::table("gd_user") -> where(['id'=>$in['create_order_user_id']]) -> find();
				}

				Db::startTrans();
//				查询库存(锁表)
				$goodsSpecWhere[] = ['id', 'eq', $in['goods_spec_id']];
				$goodsSpec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> lock(true) -> find();
				if( empty($goodsSpec) ) returnResults2('-1', '商品规格库存有误,请联系管理员');
				if( $goodsSpec['num'] < $in['num'] ) returnResults2('-1', '商品规格库存不足,请联系管理员');
				
//				减库存
				$decRe = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> update(['num'=>$goodsSpec['num'] - $in['num']]);
				if( !$decRe ){
					Db::rollback();
					returnResults2('-1', '库存减少失败,请联系管理员');
				}

				$newData = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id', 'create_order_user_id']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				$newData['code'] = date("YmdHis").rand(1000, 9999);
				$newData['order_type'] = $goods['is_be_commissioned_to_sell_sth'] == 1 ? 3 : 0;
				$newData['status'] = $in['total_price'] > 0 ? 0 : 2;
				$newData['shop_id'] = $goods['shop_id'];
				$newData['village_id'] = !empty($village) ? $village['id'] : 0;
				$newData['village_name'] = !empty($village) ? $village['name'] : '';
				$newData['goods_name'] = $goods['name'];
				$newData['goods_type'] = $goods['goods_type'];
				$newData['goods_nums'] = $in['num'];
				$newData['write_off_status'] = '-1';
				$newData['write_off_date'] = '0000-00-00 00:00:00';
				$newData['actual_price'] = $newData['total_price'];
				$newData['freight_price'] = $goods['carriage'];
				$newData['goods_spec_id'] = $goodsSpec['id'];
				$newData['goods_spec_name'] = $goodsSpec['name'];
				$newData['goods_spec_min_price_protection'] = $goodsSpec['min_price_protection'];
				$newData['goods_spec_max_price_protection'] = $goodsSpec['max_price_protection'];
				$newData['goods_create_user_id'] = $goods['create_user_id'];
				$newData['goods_create_user_name'] = $goods['create_user_name'];
				$newData['goods_create_user_shop_name'] = !empty($createGoodsShop) ? $createGoodsShop['name'] : '';
				$newData['rebate_type'] = $goods['rebate_type'];
				$newData['rebate'] = $goods['rebate'];
				$newData['create_user_id'] = $createOrderUserInfo['id'];
				$newData['create_user_name'] = $createOrderUserInfo['nickname'];
				$newData['create_user_type'] = $createOrderUserInfo['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['settle_verify_date'] = '0000-00-00 00:00:00';
				$newData['settle_verify_date2'] = '0000-00-00 00:00:00';
				$newData['payment_verify_date'] = '0000-00-00 00:00:00';
				$newData['send_goods_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_status_date'] = '0000-00-00 00:00:00';

//				生成订单
				$newOrderId = Db::table("gd_order") -> insertGetId($newData);
				if( !$newOrderId ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				
//				生成主订单的子级商品
				$subGoods = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$newData['goods_id'], 'is_delete'=>0]) -> select();
				if( !empty($subGoods) ){
					$newOrderSubgoods = [];
					foreach ($subGoods as $k => $v) {
						$newOrderSubgoods[$k]['goods_subgoods_id'] = $v['id'];
						$newOrderSubgoods[$k]['goods_id'] = $v['sub_goods_id'];
						$newOrderSubgoods[$k]['nums'] = $v['nums'];
						$newOrderSubgoods[$k]['price1'] = $v['price1'];
						$newOrderSubgoods[$k]['price2'] = $v['price2'];
						$newOrderSubgoods[$k]['order_id'] = $newOrderId;
					}
					$res = Db::table("gd_order_subgoods") -> insertAll($newOrderSubgoods);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				返现
				$rewardData = $this -> calculateReward($newOrderId);
				if( $rewardData != FALSE ){
					
					$newReward = [];
					foreach ($rewardData as $k => $v) {
						$newReward[$k]['create_order_user_id'] = $newData['create_user_id'];
						$newReward[$k]['referrer_id'] = $v['user_id'];
						$newReward[$k]['type'] = $goods['goods_type'] == 3 ? 2 : 1;
						$newReward[$k]['withdrawal_status'] = '-1';
						$newReward[$k]['rewards'] = $v['rewards'];
						$newReward[$k]['order_id'] = $newOrderId;
						$newReward[$k]['order_code'] = $newData['code'];
						$newReward[$k]['create_date'] = date("Y-m-d H:i:s", time());
						$newReward[$k]['create_order_user_id'] = $in['user_id'];
					}
					
//					批量写入奖励记录
					$re = Db::table("gd_reward") -> insertAll($newReward);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '生成明细失败,请联系管理员');
					}
				}
				
				$newIdentify = [];
				if( isset($newData['is_identify']) && $newData['is_identify'] == 1 ){
//					需要鉴定
					$newIdentify['shop_id'] = $goods['shop_id'];
					$newIdentify['shop_name'] = !empty($createGoodsShop) ? $createGoodsShop['name'] : '';
//					$newIdentify['identify_type'] = ;
//					$newIdentify['identify_type_name'] = ;
//					$newIdentify['identify_config_id1'] = ;
//					$newIdentify['identify_config_name1'] = ;
//					$newIdentify['identify_config_id2'] = ;
//					$newIdentify['identify_config_name2'] = ;
//					$newIdentify['identify_config_id3'] = ;
//					$newIdentify['identify_config_name3'] = ;
//					$newIdentify['identify_config_id4'] = ;
//					$newIdentify['identify_config_name4'] = ;
					$newIdentify['pic1'] = $goods['main_image'];
					$newIdentify['appralsal_fee'] = $newData['identify_price'];
					$newIdentify['order_id'] = $newOrderId;
					$newIdentify['goods_id'] = $newData['goods_id'];
					$newIdentify['status'] = $in['total_price'] > 0 ? 0 : 2;
					$newIdentify['goods_spec_id'] = $newData['goods_spec_id'];
					$newIdentify['create_user_id'] = $in['user_id'];
					$newIdentify['create_user_name'] = $userInfo['info']['nickname'];
					$newIdentify['create_user_type'] = $userInfo['info']['type'];
					$newIdentify['create_date'] = date("Y-m-d H:i:s", time());
					$newIdentify['pay_date'] = '0000-00-00 00:00:00';
					
					$res = Db::table("gd_identify") -> insertGetId($newIdentify);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增鉴定失败,请联系管理员');
					}
				}
				
//				if( $in['total_price'] > 0 ){
////					统一下单
//					$goodsName = $newData['goods_name'];
//					$totalPrice = $in['total_price'] * 100;
//					$openId = $userInfo['info']['open_id'];
//					$attach = ['payType'=>1, 'orderId'=>$newOrderId];
//					$re = controller("service/Wechat") -> unifiedOrder($goodsName, $totalPrice, $openId, $attach, $userInfo['info']);
//					if( $re['code'] != '1' ){
//						Db::rollback();
//						returnResults(['code'=>'-1', 'msg'=>'统一下单操作失败,请联系管理员', 'info'=>$re]);
//					}
//				}
				
				
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = $re['info'];
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'后台新增订单（主订单）',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 新增（店铺支付）
	 * 下单待付款>拉起支付>支付回调转
	 */
	public function shopPay(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'total_price', 'shop_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['shop_id']];
				$shop = Db::table("gd_shop") -> where($where) -> find();
				if( empty($shop['wechat_pay_mch_id']) || empty($shop['wechat_pay_api_v2']) ) returnResults2('-1', '下单失败,请联系管理员给商家配置微信支付参数');

				// 查询下单人和门店的关联关系
				$userShop = Db::table("gd_user_shop_relationship") -> where(['user_id'=>$in['user_id']]) -> find();

				Db::startTrans();

				$newData = [];
				$newData['code'] = date("YmdHis").rand(1000, 9999);
				$newData['order_type'] = 9;
				$newData['status'] = 0;		//待付款
				$newData['shop_id'] = $in['shop_id'];
				$newData['delivery_type_id'] = isset($in['delivery_type_id']) ? $in['delivery_type_id'] : 0;
				$newData['delivery_type_rate'] = isset($in['delivery_type_rate']) ? $in['delivery_type_rate'] : 0;
				$newData['delivery_type_rate3'] = isset($in['delivery_type_rate3']) ? $in['delivery_type_rate3'] : 0;
				$newData['source'] = isset($in['source']) ? $in['source'] : 0;
				$newData['order_user_shop_parent_user_id'] = !empty($userShop) ? $userShop['parent_user_id'] : $in['user_id'];
				$newData['goods_name'] = '线下买单';
				$newData['goods_type'] = 0;
				$newData['goods_nums'] = 1;
				$newData['write_off_status'] = '-1';
				$newData['write_off_date'] = '0000-00-00 00:00:00';
				$newData['total_price'] = $in['total_price'];
				$newData['actual_price'] = $newData['total_price'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_user_type'] = $userInfo['info']['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['settle_verify_date'] = '0000-00-00 00:00:00';
				$newData['settle_verify_date2'] = '0000-00-00 00:00:00';
				$newData['payment_verify_date'] = '0000-00-00 00:00:00';
				$newData['send_goods_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_status_date'] = '0000-00-00 00:00:00';
				$newData['check_date'] = '0000-00-00 00:00:00';
				$newData['pay_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_date'] = '0000-00-00 00:00:00';

//				生成订单
				$newOrderId = Db::table("gd_order") -> insertGetId($newData);
				if( !$newOrderId ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}

				
//				微信小程序支付
				if( isset($in['pay_type']) && $in['pay_type'] == 1 && $in['total_price'] > 0 ){
					$wechatPayCof['MCH_ID'] = $shop['wechat_pay_mch_id'];
					$wechatPayCof['SIGN_TYPE'] = 'MD5';
					$wechatPayCof['API_V2'] = $shop['wechat_pay_api_v2'];

					$weChatConfig = [];
					
//					统一下单
					$goodsName = $newData['goods_name'];
					$totalPrice = $in['total_price'] * 100;
					$openId = !empty($weChatConfig) ? $userInfo['info']['open_id2'] : $userInfo['info']['open_id'];
					$attach = ['payType'=>6, 'orderId'=>$newOrderId];
					$tradeType = isset($in['trade_type']) ? $in['trade_type'] : 'JSAPI';
					$sceneInfo = isset($in['scene_info']) ? $in['scene_info'] : '';
					$profit_sharing = 'Y';
					$re = controller("service/Wechat") -> unifiedOrder($goodsName, $totalPrice, $openId, $attach, $userInfo['info'], $weChatConfig, $tradeType, $sceneInfo, $wechatPayCof, $profit_sharing);
					if( $re['code'] != '1' ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>isset($re['msg']['err_code_des']) ? $re['msg']['err_code_des'] : '统一下单失败,请联系管理员', 'info'=>$re]);
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = isset($re['info']) ? $re['info'] : [];
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增订单（主订单）',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 余额支付
	 */
	public function rechargeBalancePay(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'order_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				Db::startTrans();
				
				$where[] = ['id', 'eq', $in['order_id']];
				$order = Db::table("gd_order") -> where($where) -> lock(true) -> find();
				if( empty($order) ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'订单数据有误,请联系管理员']);
				}
				if( $order['is_delete'] != 0 ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'订单状态有误,请联系管理员']);
				}
				if( $order['status'] != 0 ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'订单状态有误,请联系管理员']);
				}
				if( $order['create_user_id'] != $in['user_id'] ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'订单用户有误,请联系管理员']);
				}
				
//				用户余额支付
				$userWhere['id'] = $order['create_user_id'];
				$orderUser = Db::table("gd_user") -> where($userWhere) -> find();
				if( $orderUser['recharge_balance'] < $order['total_price'] ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'余额不足,请先联系管理员充值']);
				}
				
				$saveUserRe = Db::table("gd_user") -> where($userWhere) -> setDec('recharge_balance', $order['total_price']);
				if( !$saveUserRe ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'扣减用户余额失败,请联系管理员']);
				}
				
				$newRechargeRecord['user_id'] = $order['create_user_id'];
				$newRechargeRecord['first_money'] = $orderUser['recharge_balance'];
				$newRechargeRecord['after_money'] = $orderUser['recharge_balance'] - $order['total_price'];
				$newRechargeRecord['money'] = $order['total_price'];
				$newRechargeRecord['type'] = 21;
				$newRechargeRecord['state'] = 2;
				$newRechargeRecord['order_id'] = $order['id'];
				$newRechargeRecord['create_user_id'] = $order['create_user_id'];
				$newRechargeRecord['create_user_name'] = $order['create_user_name'];
				$newRechargeRecord['create_user_type'] = $order['create_user_type'];
				$newRechargeRecord['create_date'] = date("Y-m-d H:i:s", time());
				$res = Db::table("gd_recharge_record") -> insertGetId($newRechargeRecord);
				if( !$res ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'生成余额变动记录失败,请联系管理员']);
				}
				
				$saveOrder['status'] = 2;
				$saveOrder['write_off_status'] = $order['goods_type'] == 2 ? '0' : $order['write_off_status'];
				$saveOrder['actual_price'] = $order['total_price'];
				$saveOrder['pay_type'] = 9;
				$saveOrder['pay_code'] = date("Y-m-d H:i:s", time()).rand(1000, 9999);
				$saveOrder['pay_date'] = date("Y-m-d H:i:s", time());
				$saveOrderRe = Db::table("gd_order") -> where(['id'=>$order['id']]) -> update($saveOrder);
				if( !$saveOrderRe ){
					Db::rollback();
					returnResults(['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员']);
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = isset($re['info']) ? $re['info'] : [];
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'余额支付',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 根据收货地址+主商品id找商家的商品
	 */
	private function searchShopGoods($province, $city, $area, $goods_spec_id){
		$shopWhere['province'] = $province;
		$shopWhere['city'] = $city;
		$shopWhere['area'] = $area;
		$shop = Db::table("gd_shop") -> where($shopWhere) -> find();
		if( empty($shop) ) return false;
		
		$goodsSpecWhere['parent_id'] = $goods_spec_id;
		$goodsSpecWhere['is_delete'] = 0;
		$goodsSpecWhere['create_user_id'] = $shop['create_user_id'];
		$spec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> find();
		if( empty($spec) ) return false;
		
		if( $spec['num2'] > 0 && $spec['num3'] > 0 ){
//			按照商家的发货方式顺序获取发货方式id
			$shopDeliveryType = Db::table("gd_shop_delivery_type") -> where(['shop_id'=>$shop['id']]) -> order("sort asc") -> find();
			if( empty($shopDeliveryType) ) return false;
			$delivery_type_id = $shopDeliveryType['delivery_type_config_id'];
		}else if( $spec['num2'] > 0 && $spec['num3'] == 0 ){
			$delivery_type_id = 3;
		}else if( $spec['num2'] == 0 && $spec['num3'] > 0 ){
			$delivery_type_id = 2;
		}else if( $spec['num2'] == 0 && $spec['num3'] == 0 ){
			return false;
		}
		
//		返回：商品id、规格id、商店id、发货方式id
		return ['goods_id'=>$spec['goods_id'], 'goods_spec_id'=>$spec['id'], 'shop_id'=>$shop['id'], 'delivery_type_config_id'=>$delivery_type_id];
	}
	
	/**
	 * 新增（主订单）
	 * 下单待付款>拉起支付>支付回调转已付款待发货
	 */
	public function add(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'goods_id', 'goods_spec_id', 'num', 'total_price'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
//				根据收货地址+主商品id找商家的商品
				if( isset($in['source']) && $in['source'] == 2 && isset($in['receiving_province']) && isset($in['receiving_city']) && isset($in['receiving_area']) ){
					$shopGoodsInfo = $this -> searchShopGoods($in['receiving_province'], $in['receiving_city'], $in['receiving_area'], $in['goods_spec_id']);
					if( $shopGoodsInfo != false ){
						$in['goods_id'] = $shopGoodsInfo['goods_id'];							//商品id
						$in['goods_spec_id'] = $shopGoodsInfo['goods_spec_id'];					//商品规格id
						$in['shop_id'] = $shopGoodsInfo['shop_id'];								//商店id
						$in['delivery_type_id'] = $shopGoodsInfo['delivery_type_config_id'];	//发货方式id
					}
				}
				
				$where[] = ['id', 'eq', $in['goods_id']];
				$goods = Db::table("gd_goods") -> where($where) -> find();
				
				$createGoodsShop = Db::table("gd_shop") -> where(['create_user_id'=>$goods['create_user_id']]) -> find();
				
				$village = [];
				if( isset($in['village_id']) && $in['village_id'] > 0 ){
					$village = Db::table("gd_village") -> where(['id'=>$in['village_id']]) -> find();
				}
				
				if( isset($in['parent_user_id']) && $in['parent_user_id'] > 0 ){
//					存在推荐人id，读取下单人订单数据及下单人用户数据
					if( $userInfo['info']['referrer_id'] == 0 ){
						$userOrder = Db::table("gd_order") -> where(['is_delete'=>0, 'create_user_id'=>$userInfo['info']['id']]) -> find();
						if( empty($userOrder) ){
						}else{
							$in['parent_user_id'] = 0;
						}
					}else{
						$in['parent_user_id'] = 0;
					}
				}
				
				Db::startTrans();
//				查询库存(锁表)
				$goodsSpecWhere[] = ['id', 'eq', $in['goods_spec_id']];
				$goodsSpec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> lock(true) -> find();
				if( empty($goodsSpec) ) returnResults2('-1', '商品规格库存有误,请联系管理员');
				if( $in['source'] == 2 && $goodsSpec['num'] < $in['num'] ) returnResults2('-1', '该地区商品规格库存不足,请联系管理员及时补货');
//				商家发货
				if( $in['source'] == 2 && isset($in['delivery_type_id']) && $in['delivery_type_id'] == 2 && $goodsSpec['num3'] < $in['num'] ) returnResults2('-1', '该地区商品规格库存不足(实仓),请联系管理员及时补货');
//				云仓发货
				if( $in['source'] == 2 && isset($in['delivery_type_id']) && $in['delivery_type_id'] == 3 && $goodsSpec['num2'] < $in['num'] ) returnResults2('-1', '该地区商品规格库存不足(云仓),请联系管理员及时补货');
				
//				减库存
				$saveGoodsSpec['num'] = $goodsSpec['num'] - $in['num'];
//				商家端进货
				if( isset($in['source']) && $in['source'] == 21 ){
//					扣减实仓
					$saveGoodsSpec['num3'] = $goodsSpec['num3'] - $in['num'];
				}
//				用户端购买
				if( isset($in['source']) && $in['source'] == 2 ){
//					根据库存的收货方式扣减商家库存
					if( isset($in['delivery_type_id']) && $in['delivery_type_id'] == 1 ) $saveGoodsSpec['num3'] = $goodsSpec['num3'] - $in['num'];		//总平台发货,扣实仓
					if( isset($in['delivery_type_id']) && $in['delivery_type_id'] == 2 ) $saveGoodsSpec['num3'] = $goodsSpec['num3'] - $in['num'];
					if( isset($in['delivery_type_id']) && $in['delivery_type_id'] == 3 ) $saveGoodsSpec['num2'] = $goodsSpec['num2'] - $in['num'];
				}
				$decRe = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> update($saveGoodsSpec);
				if( !$decRe ){
					Db::rollback();
					returnResults2('-1', '库存减少失败,请联系管理员');
				}
				
//				发货类型配置项
//				$deliveryTypeConfig = [];
//				if( $goodsSpec['delivery_type_id'] > 0 ) $deliveryTypeConfig = Db::table("gd_delivery_type_config") -> where(['id'=>$goodsSpec['delivery_type_id']]) -> find();

				$newData = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id', 'weChatConfigName']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				$newData['code'] = date("YmdHis").rand(1000, 9999);
				$newData['order_type'] = $goods['is_be_commissioned_to_sell_sth'] == 1 ? 3 : 0;
				$newData['status'] = $in['total_price'] > 0 ? 0 : 2;
				$newData['shop_id'] = $goods['shop_id'];
				$newData['delivery_type_id'] = isset($in['delivery_type_id']) ? $in['delivery_type_id'] : 1;
				$newData['delivery_type_rate'] = isset($in['delivery_type_rate']) ? $in['delivery_type_rate'] : 0;
				$newData['delivery_type_rate3'] = isset($in['delivery_type_rate3']) ? $in['delivery_type_rate3'] : 0;
				$newData['source'] = isset($in['source']) ? $in['source'] : 0;
				$newData['village_id'] = !empty($village) ? $village['id'] : 0;
				$newData['village_name'] = !empty($village) ? $village['name'] : '';
				$newData['parent_goods_id'] = $goods['parent_id'];
				$newData['goods_name'] = $goods['name'];
				$newData['goods_type'] = $goods['goods_type'];
				$newData['goods_nums'] = $in['num'];
				$newData['write_off_status'] = '-1';
				$newData['write_off_date'] = '0000-00-00 00:00:00';
				$newData['actual_price'] = $newData['total_price'];
				$newData['freight_price'] = $goods['carriage'];
				$newData['goods_spec_id'] = $goodsSpec['id'];
				$newData['goods_spec_name'] = $goodsSpec['name'];
				$newData['goods_spec_min_price_protection'] = $goodsSpec['min_price_protection'];
				$newData['goods_spec_max_price_protection'] = $goodsSpec['max_price_protection'];
				$newData['goods_create_user_id'] = $goods['create_user_id'];
				$newData['goods_create_user_name'] = $goods['create_user_name'];
				$newData['goods_create_user_shop_name'] = !empty($createGoodsShop) ? $createGoodsShop['name'] : '';
				$newData['rebate_type'] = $goods['rebate_type'];
				$newData['rebate'] = $goods['rebate'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_user_type'] = $userInfo['info']['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['settle_verify_date'] = '0000-00-00 00:00:00';
				$newData['settle_verify_date2'] = '0000-00-00 00:00:00';
				$newData['payment_verify_date'] = '0000-00-00 00:00:00';
				$newData['send_goods_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_status_date'] = '0000-00-00 00:00:00';
				$newData['check_date'] = '0000-00-00 00:00:00';
				$newData['pay_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_date'] = '0000-00-00 00:00:00';
				$newData['parent_user_id'] = isset($in['parent_user_id']) ? $in['parent_user_id'] : '0';

//				生成订单
				$newOrderId = Db::table("gd_order") -> insertGetId($newData);
				if( !$newOrderId ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				
//				生成主订单的子级商品
				$subGoods = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$newData['goods_id'], 'is_delete'=>0]) -> select();
				if( !empty($subGoods) ){
					$newOrderSubgoods = [];
					foreach ($subGoods as $k => $v) {
						$newOrderSubgoods[$k]['goods_subgoods_id'] = $v['id'];
						$newOrderSubgoods[$k]['goods_id'] = $v['sub_goods_id'];
						$newOrderSubgoods[$k]['nums'] = $v['nums'];
						$newOrderSubgoods[$k]['price1'] = $v['price1'];
						$newOrderSubgoods[$k]['price2'] = $v['price2'];
						$newOrderSubgoods[$k]['order_id'] = $newOrderId;
					}
					$res = Db::table("gd_order_subgoods") -> insertAll($newOrderSubgoods);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增失败,请联系管理员');
					}
				}
				
//				用户端下单才返现
				if( $in['source'] == 2 ) {
					$rewardData = $this -> calculateReward2($newOrderId);
					
					if( $rewardData != FALSE ){
						
						$newReward = [];
						foreach ($rewardData as $k => $v) {
							$newReward[$k]['create_order_user_id'] = $newData['create_user_id'];
							$newReward[$k]['referrer_id'] = $v['user_id'];
							$newReward[$k]['type'] = $goods['goods_type'] == 3 ? 2 : 1;
							$newReward[$k]['withdrawal_status'] = '-1';
							$newReward[$k]['rewards'] = $v['rewards'];
							$newReward[$k]['order_id'] = $newOrderId;
							$newReward[$k]['order_code'] = $newData['code'];
							$newReward[$k]['create_date'] = date("Y-m-d H:i:s", time());
							$newReward[$k]['create_order_user_id'] = $in['user_id'];
						}
						
	//					批量写入奖励记录
						$re = Db::table("gd_reward") -> insertAll($newReward);
						if( !$re ) {
							Db::rollback();
							returnResults2('-1', '生成明细失败,请联系管理员');
						}
					}
				}
				
				$newIdentify = [];
				if( isset($newData['is_identify']) && $newData['is_identify'] == 1 ){
//					需要鉴定
					$newIdentify['shop_id'] = $goods['shop_id'];
					$newIdentify['shop_name'] = !empty($createGoodsShop) ? $createGoodsShop['name'] : '';
//					$newIdentify['identify_type'] = ;
//					$newIdentify['identify_type_name'] = ;
//					$newIdentify['identify_config_id1'] = ;
//					$newIdentify['identify_config_name1'] = ;
//					$newIdentify['identify_config_id2'] = ;
//					$newIdentify['identify_config_name2'] = ;
//					$newIdentify['identify_config_id3'] = ;
//					$newIdentify['identify_config_name3'] = ;
//					$newIdentify['identify_config_id4'] = ;
//					$newIdentify['identify_config_name4'] = ;
					$newIdentify['pic1'] = $goods['main_image'];
					$newIdentify['appralsal_fee'] = $newData['identify_price'];
					$newIdentify['order_id'] = $newOrderId;
					$newIdentify['goods_id'] = $newData['goods_id'];
					$newIdentify['status'] = $in['total_price'] > 0 ? 0 : 2;
					$newIdentify['goods_spec_id'] = $newData['goods_spec_id'];
					$newIdentify['create_user_id'] = $in['user_id'];
					$newIdentify['create_user_name'] = $userInfo['info']['nickname'];
					$newIdentify['create_user_type'] = $userInfo['info']['type'];
					$newIdentify['create_date'] = date("Y-m-d H:i:s", time());
					$newIdentify['pay_date'] = '0000-00-00 00:00:00';
					
					$res = Db::table("gd_identify") -> insertGetId($newIdentify);
					if( !$res ) {
						Db::rollback();
						returnResults2('-1', '新增鉴定失败,请联系管理员');
					}
				}
				
//				微信小程序支付
				if( isset($in['pay_type']) && $in['pay_type'] == 1 && $in['total_price'] > 0 ){
					$weChatConfig = [];
					if( isset($in['weChatConfigName']) && $in['weChatConfigName'] == 'WECHAT_MIN2' ) $weChatConfig = config("WECHAT_MIN2");
					
//					统一下单
					$goodsName = $newData['goods_name'];
					$totalPrice = $in['total_price'] * 100;
					$openId = !empty($weChatConfig) ? $userInfo['info']['open_id2'] : $userInfo['info']['open_id'];
					$attach = ['payType'=>1, 'orderId'=>$newOrderId];
					$tradeType = isset($in['trade_type']) ? $in['trade_type'] : 'JSAPI';
					$sceneInfo = isset($in['scene_info']) ? $in['scene_info'] : '';
					$re = controller("service/Wechat") -> unifiedOrder($goodsName, $totalPrice, $openId, $attach, $userInfo['info'], $weChatConfig, $tradeType, $sceneInfo);
					if( $re['code'] != '1' ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'统一下单操作失败,请联系管理员', 'info'=>$re]);
					}
				}
//				用户余额支付
				if( isset($in['pay_type']) && $in['pay_type'] == 9 && $in['total_price'] > 0 ){
					$userWhere['id'] = $newData['create_user_id'];
					$orderUser = Db::table("gd_user") -> where($userWhere) -> find();
					if( $orderUser['recharge_balance'] < $newData['total_price'] ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'余额不足,请先联系管理员充值']);
					}
					
					$saveUserRe = Db::table("gd_user") -> where($userWhere) -> setDec('recharge_balance', $newData['total_price']);
					if( !$saveUserRe ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'扣减用户余额失败,请联系管理员']);
					}
					
					$newRechargeRecord['user_id'] = $newData['create_user_id'];
					$newRechargeRecord['first_money'] = $orderUser['recharge_balance'];
					$newRechargeRecord['after_money'] = $orderUser['recharge_balance'] - $newData['total_price'];
					$newRechargeRecord['money'] = $newData['total_price'];
					$newRechargeRecord['type'] = 21;
					$newRechargeRecord['state'] = 2;
					$newRechargeRecord['order_id'] = $newOrderId;
					$newRechargeRecord['create_user_id'] = $newData['create_user_id'];
					$newRechargeRecord['create_user_name'] = $newData['create_user_name'];
					$newRechargeRecord['create_user_type'] = $newData['create_user_type'];
					$newRechargeRecord['create_date'] = date("Y-m-d H:i:s", time());
					$res = Db::table("gd_recharge_record") -> insertGetId($newRechargeRecord);
					if( !$res ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'生成余额变动记录失败,请联系管理员']);
					}
					
					$saveOrder['status'] = 2;
					$saveOrder['write_off_status'] = $newData['goods_type'] == 2 ? '0' : $newData['write_off_status'];
					$saveOrder['actual_price'] = $in['total_price'];
					$saveOrder['pay_type'] = 9;
					$saveOrder['pay_code'] = date("Y-m-d H:i:s", time()).rand(1000, 9999);
					$saveOrder['pay_date'] = date("Y-m-d H:i:s", time());
					$saveOrderRe = Db::table("gd_order") -> where(['id'=>$newOrderId]) -> update($saveOrder);
					if( !$saveOrderRe ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'变更订单失败,请联系管理员']);
					}
				}
				
				
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = isset($re['info']) ? $re['info'] : [];
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增订单（主订单）',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 新增（子订单）
	 * 下单待付款>拉起支付>支付回调转已付款待发货
	 */
	public function addSubOrder(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'goods_id', 'goods_spec_id', 'num', 'total_price', 'parent_user_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
				$where[] = ['id', 'eq', $in['goods_id']];
				$goods = Db::table("gd_goods") -> where($where) -> find();
				
				if($in['num'] != 1) returnResults2('-1', '特殊商品只能库存数只能选1,请联系管理员');
				
				$createGoodsShop = Db::table("gd_shop") -> where(['create_user_id'=>$goods['create_user_id']]) -> find();
				
				$village = [];
				if( isset($in['village_id']) && $in['village_id'] > 0 ){
					$village = Db::table("gd_village") -> where(['id'=>$in['village_id']]) -> find();
				}
				
				$orderSubgoodsWhere[] = ['b.create_user_id', 'eq', $in['parent_user_id']];
				$orderSubgoodsWhere[] = ['b.status', 'eq', 1];
				$orderSubgoodsWhere[] = ['a.buy_nums', 'exp', Db::raw("< a.nums")];
				$orderSubgoods = Db::table("gd_order_subgoods") -> alias('a')
											-> join('gd_order b', 'a.order_id = b.id')
											-> field(['a.*'])
							                -> where($orderSubgoodsWhere)
											-> find();
				if( empty($orderSubgoods) ) returnResults2('-1', '主订单关联的子级商品有误,请联系管理员');
				if( $orderSubgoods['buy_nums'] >= $orderSubgoods['nums'] ) returnResults2('-1', '操作失败,主订单关联的子级商品数量不足');
				if( ($orderSubgoods['buy_nums'] + $in['num']) > $orderSubgoods['nums'] ) returnResults2('-1', '操作失败,主订单关联的子级商品数量不足');
				$order_subgoods_id = $orderSubgoods['id'];

				Db::startTrans();
//				查询规格(锁表)
				$goodsSpecWhere[] = ['id', 'eq', $in['goods_spec_id']];
				$goodsSpec = Db::table("gd_goods_spec") -> where($goodsSpecWhere) -> lock(true) -> find();
				if( empty($goodsSpec) ) returnResults2('-1', '商品规格有误,请联系管理员');
				
//				减库存(子商品)
				$decRe = Db::table("gd_order_subgoods") -> where(['id'=>$orderSubgoods['id']]) -> update(['buy_nums'=>$orderSubgoods['buy_nums'] + $in['num']]);
				if( !$decRe ){
					Db::rollback();
					returnResults2('-1', '库存减少失败,请联系管理员');
				}

				$newData = [];
				foreach ($in as $k => $v) {
					if( !in_array($k, ['id', 'user_id', 'parent_user_id', 'weChatConfigName']) ){
						$newData[$k] = is_array($v) ? json_encode($v, JSON_UNESCAPED_UNICODE) : $v;
					}
				}
				$newData['code'] = date("YmdHis").rand(1000, 9999);
				$newData['order_type'] = $goods['is_be_commissioned_to_sell_sth'] == 1 ? 3 : 0;
				$newData['status'] = $in['total_price'] > 0 ? 0 : 2;
				$newData['shop_id'] = $goods['shop_id'];
				$newData['delivery_type_id'] = isset($in['delivery_type_id']) ? $in['delivery_type_id'] : 0;
				$newData['delivery_type_rate'] = isset($in['delivery_type_rate']) ? $in['delivery_type_rate'] : 0;
				$newData['delivery_type_rate3'] = isset($in['delivery_type_rate3']) ? $in['delivery_type_rate3'] : 0;
				$newData['source'] = isset($in['source']) ? $in['source'] : 0;
				$newData['village_id'] = !empty($village) ? $village['id'] : 0;
				$newData['village_name'] = !empty($village) ? $village['name'] : '';
				$newData['goods_name'] = $goods['name'];
				$newData['goods_type'] = $goods['goods_type'];
				$newData['goods_nums'] = $in['num'];
				$newData['write_off_status'] = '-1';
				$newData['write_off_date'] = '0000-00-00 00:00:00';
				$newData['actual_price'] = $newData['total_price'];
				$newData['freight_price'] = $goods['carriage'];
				$newData['goods_spec_id'] = $goodsSpec['id'];
				$newData['goods_spec_name'] = $goodsSpec['name'];
				$newData['goods_spec_min_price_protection'] = $goodsSpec['min_price_protection'];
				$newData['goods_spec_max_price_protection'] = $goodsSpec['max_price_protection'];
				$newData['goods_create_user_id'] = $goods['create_user_id'];
				$newData['goods_create_user_name'] = $goods['create_user_name'];
				$newData['goods_create_user_shop_name'] = !empty($createGoodsShop) ? $createGoodsShop['name'] : '';
				$newData['rebate_type'] = $goods['rebate_type'];
				$newData['parent_order_id'] = $orderSubgoods['order_id'];
				$newData['order_subgoods_id'] = $orderSubgoods['id'];
				$newData['rebate'] = $goods['rebate'];
				$newData['create_user_id'] = $in['user_id'];
				$newData['create_user_name'] = $userInfo['info']['nickname'];
				$newData['create_user_type'] = $userInfo['info']['type'];
				$newData['create_date'] = date("Y-m-d H:i:s", time());
				$newData['settle_verify_date'] = '0000-00-00 00:00:00';
				$newData['settle_verify_date2'] = '0000-00-00 00:00:00';
				$newData['payment_verify_date'] = '0000-00-00 00:00:00';
				$newData['send_goods_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_status_date'] = '0000-00-00 00:00:00';
				$newData['check_date'] = '0000-00-00 00:00:00';
				$newData['pay_date'] = '0000-00-00 00:00:00';
				$newData['refund_applyfor_date'] = '0000-00-00 00:00:00';

//				生成订单
				$newOrderId = Db::table("gd_order") -> insertGetId($newData);
				if( !$newOrderId ) {
					Db::rollback();
					returnResults2('-1', '新增失败,请联系管理员');
				}
				
//				生成主订单的子级商品
//				$subGoods = Db::table("gd_goods_subgoods") -> where(['goods_id'=>$newData['goods_id']]) -> select();
//				if( !empty($subGoods) ){
//					$newOrderSubgoods = [];
//					foreach ($subGoods as $k => $v) {
//						$newOrderSubgoods[$k]['goods_subgoods_id'] = $v['id'];
//						$newOrderSubgoods[$k]['nums'] = $v['nums'];
//						$newOrderSubgoods[$k]['price1'] = $v['price1'];
//						$newOrderSubgoods[$k]['price2'] = $v['price2'];
//						$newOrderSubgoods[$k]['order_id'] = $newOrderId;
//					}
//				}

//				返现
				$rewardData = $this -> calculateReward($newOrderId, $in['parent_user_id']);
				if( $rewardData != FALSE ){
					
					$newReward = [];
					foreach ($rewardData as $k => $v) {
						$newReward[$k]['create_order_user_id'] = $newData['create_user_id'];
						$newReward[$k]['referrer_id'] = $v['user_id'];
						$newReward[$k]['type'] = $goods['goods_type'] == 3 ? 2 : 1;
						$newReward[$k]['withdrawal_status'] = '-1';
						$newReward[$k]['rewards'] = $v['rewards'];
						$newReward[$k]['order_id'] = $newOrderId;
						$newReward[$k]['order_code'] = $newData['code'];
						$newReward[$k]['create_date'] = date("Y-m-d H:i:s", time());
						$newReward[$k]['create_order_user_id'] = $in['user_id'];
					}
					
//					批量写入奖励记录
					$re = Db::table("gd_reward") -> insertAll($newReward);
					if( !$re ) {
						Db::rollback();
						returnResults2('-1', '生成明细失败,请联系管理员');
					}
				}
				
				if( $in['total_price'] > 0 ){
					$weChatConfig = [];
					if( isset($in['weChatConfigName']) && $in['weChatConfigName'] == 'WECHAT_MIN2' ) $weChatConfig = config("WECHAT_MIN2");
					
//					统一下单
					$goodsName = $newData['goods_name'];
					$totalPrice = $in['total_price'] * 100;
					$openId = !empty($weChatConfig) ? $userInfo['info']['open_id2'] : $userInfo['info']['open_id'];
					$attach = ['payType'=>1, 'orderId'=>$newOrderId];
					$tradeType = isset($in['trade_type']) ? $in['trade_type'] : 'JSAPI';
					$sceneInfo = isset($in['scene_info']) ? $in['scene_info'] : '';
					$re = controller("service/Wechat") -> unifiedOrder($goodsName, $totalPrice, $openId, $attach, $userInfo['info'], $weChatConfig, $tradeType, $sceneInfo);
					if( $re['code'] != '1' ){
						Db::rollback();
						returnResults(['code'=>'-1', 'msg'=>'统一下单操作失败,请联系管理员', 'info'=>$re]);
					}
				}
				
				Db::commit();
				
				$outArr['code'] = '1';
				$outArr['info'] = $re['info'];
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'新增订单（子订单）',
						'business_type'=>1,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}

	/**
	 * 微信统一下单（待支付的订单付款）
	 */
	public function unifiedOrderState1(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['user_id', 'order_id'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$userInfo = $this -> getUserInfo();
				
//				获取订单
				$where[] = ['id', 'eq', $in['order_id']];
				$order = Db::table("gd_order") -> where($where) -> find();
				if( empty($order) ) returnResults2('-1', '操作失败,查询订单数据有误,请联系管理员');
				
//				统一下单
				$goodsName = $order['goods_name'];
				$totalPrice = $order['total_price'] * 100;
				
				
//				$totalPrice = 1;						///////测试一分
				
				$weChatConfig = [];
				if( isset($in['weChatConfigName']) && $in['weChatConfigName'] == 'WECHAT_MIN2' ) $weChatConfig = config("WECHAT_MIN2");
				
				$openId = !empty($weChatConfig) ? $userInfo['info']['open_id2'] : $userInfo['info']['open_id'];
				$attach = ['payType'=>1, 'orderId'=>$order['id']];
				$tradeType = isset($in['trade_type']) ? $in['trade_type'] : 'JSAPI';
				$sceneInfo = isset($in['scene_info']) ? $in['scene_info'] : '';
				$re = controller("service/Wechat") -> unifiedOrder($goodsName, $totalPrice, $openId, $attach, $userInfo['info'], $weChatConfig, $tradeType, $sceneInfo);
				if( $re['code'] != '1' ){
					returnResults2('-1', '统一下单操作失败,请联系管理员');
				}
				
				$outArr['code'] = '1';
				$outArr['info'] = $re['info'];
				
//				写入操作日志
				$old_data_json = $order;
				controller("service/OperLog") -> logs(
					[
						'title'=>'微信统一下单（待支付的订单付款）',
						'business_type'=>3,
						'oper_name'=>$userInfo['info']['nickname'],
						'oper_user_id'=>$userInfo['info']['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>